2
votes

This question concerns the pthread API for Posix systems.

My understanding is that when waiting for a conditional variable, or more specifically a pthread_cond_t, the flow goes something like this.

// imagine the mutex is named mutex and the conditional variable is named cond

// first we lock the mutex to prevent race conditions
pthread_mutex_lock(&mutex);

// then we wait for the conditional variable, releasing the mutex
pthread_cond_wait(&cond, &mutex);

// after we're done waiting we own the mutex again have to release it
pthread_mutex_unlock(&mutex);

In this example we stop waiting for the mutex when some other thread follows a procedure like this.

// lock the mutex to prevent race conditions
pthread_mutex_lock(&mutex);

// signal the conditional variable, giving up control of the mutex
pthread_cond_signal(&cond);

My understanding is that if multiple threads are waiting some kind of scheduling policy will be applied, and whichever thread is unblocked also gets back the associated mutex.

Now what I don't understand is what happens when some thread calls pthread_cond_broadcast(&cond) to awake all of the threads waiting on the conditional variable.

Does only one thread get to own the mutex? Do I need to wait in a fundamentally different manner when waiting for a broadcast than when waiting for a signal (i.e. by not calling pthread_mutex_unlock unless I can confirm this thread acquired the mutex)? Or am I wrong in my whole understanding of how the mutex/cond relationship works?

Most importantly, if (as I think is probably the case) pthread_cond_broadcast causes threads to compete for the associated mutex as if they had all tried to lock it, does that mean only one thread will really wake up?

1

1 Answers

3
votes

When some thread calls pthread_cond_broadcast while holding the mutex, it holds the mutex. Which means that once pthread_cond_broadcast returns, it still owns the mutex.

The other threads will all wake up, try to lock the mutex, then go to sleep to wait for the mutex to become available.

If you call pthread_cond_broadcast while not holding the mutex, then one of the other threads will be able to lock the mutex immediately. All the others will have to wait to lock the mutex.