What happens if a pthread condition variable is signaled but the mutex is locked?

StackOverflow https://stackoverflow.com/questions/23553330

  •  18-07-2023
  •  | 
  •  

Question

Consider the following:

pthread_mutex_t m;
pthread_cond_t c;

//a bunch of passenger threads will all be doing this
pthread_mutex_lock(&m); //passengers join the queue for boarding one at a time
pthread_cond_wait(&c, &m); //joined queue, mutex now unlocked allowing other passengers to join queue
//wait for a ride thread to signal the variable (representing the queue), allowing passengers to board one at a time
//
//Do some work in here required for boarding the ride
//
pthread_mutex_unlock(&m); //allow the next passenger to do the work required to board

Can I guarantee that only one passenger will be able to access the "do some work here" part at a time? From my understanding, once the condition variable is signaled, that thread will relock the mutex and proceed on. What happens if after one thread gets signaled and starts doing work, the ride thread signals the cond variable again? Will the second thread wait for the first thread to unlock the mutex, or will both threads now be in the "do some work here" part?

Was it helpful?

Solution

Consider if you used pthread_cond_broadcast instead of pthread_cond_signal. All threads that are in a pthread_cond_wait on the conditions are signaled to wake up. Only one of them can because in order to exit pthread_cond_wait they each must reacquire the mutex. The one that gets the mutex finishes and unlocks the mutex, and then the next one gets the mutex. Despite being a performance hit from waking more threads than needed, this should not change the correct function of code that is using of pthread_cond_wait properly.

From the manpage for pthread_cond_wait:

    "Spurious wakeups from the pthread_cond_timedwait() or pthread_cond_wait() functions may occur."

When a thread returns from a pthread_cond_wait it should check that there is data (that was protected by the mutex) that indicates it can actually proceed. Typicaly this involves the thread that performed the pthread_cond_signal incrementing a count or setting a flag (protected by the mutex), and the thread that received the pthread_cond_wait looping on the the wait call while the flag value is zero, and if its not zero decrementing the flag before it leaves its mutex protected section.

I don't see the expected loop, nor the signaling value addressed in the snippit you provided.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top