PDA

View Full Version : A Question about Locks in Linux Threads



Overworked_PhD
11-04-2007, 06:33 PM
In a lot of the thread code, I see something like the following



int queue_int(struct queue *qp)
{
int err;
qp->head = NULL;
qp->tail = NULL;

err = pthread_rwlock_init(&qp->qp->lock, NULL);

/*more code*/

}


How come the the lock is placed AFTER head and tail are set to NULL? I
guess I don't understand the reason why you wouldn't place the lock
BEFORE setting head and tail to NULL.

CornedBee
11-05-2007, 12:12 AM
It's not a locking operation. It merely initializes the lock that is used later. Because this is an initialization operation, there is no possibility of another thread using the same data structure yet, so no need for synchronization.

matsp
11-05-2007, 03:20 AM
Note also that
pthread_rwlock_init() is just setting up the lock, not locking anything. It needs to be done before any code can USE the lock.

So, as part of "creating" (or initializing) the queue, it's a good idea to create the lock. Should this be the FIRST ever thing, or some time after the first few lines? As long as no one tries to use the lock (or any other part of the queue, really) before the initialization is finished, it really doesn't matter. My suspicion is that you'll find that this initialization is done while the main thread is the only thread in the system, thus avoiding any races - that is of course just a guess.

--
Mats