Thread: A Question about Locks in Linux Threads

  1. #1
    Join Date
    May 2007
    Berkeley, CA

    A Question about Locks in Linux Threads

    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.

  2. #2
    Cat without Hat CornedBee's Avatar
    Join Date
    Apr 2003
    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.
    All the buzzt!

    "There is not now, nor has there ever been, nor will there ever be, any programming language in which it is the least bit difficult to write bad code."
    - Flon's Law

  3. #3
    Kernel hacker
    Join Date
    Jul 2007
    Farncombe, Surrey, England
    Note also that
    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.

    Compilers can produce warnings - make the compiler programmers happy: Use them!
    Please don't PM me for help - and no, I don't do help over instant messengers.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Threads question
    By tezcatlipooca in forum C++ Programming
    Replies: 1
    Last Post: 04-07-2007, 05:10 AM
  2. Question about Multiple threads and ring buffer.
    By qingxing2005 in forum C Programming
    Replies: 2
    Last Post: 01-15-2007, 12:30 AM
  3. callbacks and threads - technical question
    By Jumper in forum Windows Programming
    Replies: 2
    Last Post: 07-11-2004, 12:09 AM
  4. question from linux board ( not os dependant )
    By crypto in forum C Programming
    Replies: 4
    Last Post: 11-15-2002, 02:09 AM
  5. Question about LINUX
    By River21 in forum A Brief History of
    Replies: 0
    Last Post: 09-17-2001, 06:39 PM