Search code examples
pthreadsmutexcondition-variable

Mutex are needed to protect the Condition Variables


As it is said that Mutex are needed to protect the Condition Variables.

Is the reference here to the actual condition variable declared as pthread_cond_t
OR
A normal shared variable count whose values decide the signaling and wait.
?


Solution

  • is the reference here to the actual condition variable declared as pthread_cond_t or a normal shared variable count whose values decide the signaling and wait?

    The reference is to both.

    The mutex makes it so, that the shared variable (count in your question) can be checked, and if the value of that variable doesn't meet the desired condition, the wait that is performed inside pthread_cond_wait() will occur atomically with respect to that check.

    The problem being solved with the mutex is that you have two separate operations that need to be atomic:

    1. check the condition of count
    2. wait inside of pthread_cond_wait() if the condition isn't met yet.

    A pthread_cond_signal() doesn't 'persist' - if there are no threads waiting on the pthread_cond_t object, a signal does nothing. So if there wasn't a mutex making the two operations listed above atomic with respect to one another, you could find yourself in the following situation:

    • Thread A wants to do something once count is non-zero
    • Thread B will signal when it increments count (which will set count to something other than zero)

      1. thread "A" checks count and finds that it's zero
      2. before "A" gets to call pthread_cond_wait(), thread "B" comes along and increments count to 1 and calls pthread_cond_signal(). That call actually does nothing of consequence since "A" isn't waiting on the pthread_cond_t object yet.
      3. "A" calls pthread_cond_wait(), but since condition variable signals aren't remembered, it will block at this point and wait for the signal that has already come and gone.

    The mutex (as long as all threads are following the rules) makes it so that item #2 cannot occur between items 1 and 3. The only way that thread "B" will get a chance to increment count is either before A looks at count or after "A" is already waiting for the signal.