pthread condition variables on Linux, odd behaviour

前端 未结 4 889
情深已故
情深已故 2021-01-20 01:49

I\'m synchronizing reader and writer processes on Linux.

I have 0 or more process (the readers) that need to sleep until they are woken up, read a resource, go back

4条回答
  •  谎友^
    谎友^ (楼主)
    2021-01-20 02:17

    Do you test for some condition before your process actually call pthread_cond_wait() ? I am asking because, it's a very common mistake : Your process must not call wait() unless you are sure that some process will call signal() (or broadcast()) later.

    concidering this code (from pthread_cond_wait man page) :

              pthread_mutex_lock(&mut);
              while (x <= y) {
                      pthread_cond_wait(&cond, &mut);
              }
              /* operate on x and y */
              pthread_mutex_unlock(&mut);
    

    If your omit the while test, and just signal from another process whenever your (x <= y) condition is true, it won't work since the signal only wakes up the process the are already waiting. If signal() called before the other process calls wait() the signal will be lost and the waiting process will be waiting forever.

    EDIT : About the while loop. When you are signaling one process from another process it is set on the ''ready list'' but not necessarily scheduled and your condition (x <= y) may be change again since no one holds the lock. That's why you need to check for your condition each time you are about to wait. It should always be wakeup -> check if the condition is still true -> do work.

    hope it's clear.

提交回复
热议问题