This question is regarding the pthread tutorial in llnl. Say there are three threads.
Thread 1:
pthread_mutex_lock(&mutex)
do_something...
if condition
pthread_cond_signal(&con)
pthread_mutex_unlock(&mutex)
repeat
Thread 2:
pthread_mutex_lock(&mutex)
do_something...
if condition
pthread_cond_signal(&con)
pthread_mutex_unlock(&mutex)
repeat
Thread 3:
pthread_mutex_lock(&mutex)
while(condition not holds)
pthread_cond_wait(&con)
do_something...
pthread_mutex_unlock(&mutex)
Assume that Thread1 checks that condition is satisfied and then sends signal to wake up Thread3. Finally it unlocks the mutex. But at the same time, Thread 2 is trying to lock the mutex.
My question is: is there any guarantee that Thread3 will always win in the competition?
If not then after Thread2 do_something..., the condition variable may be changed, then when Thread3 gets to lock the mutex, the condition variable is different from what it expects.
pthread_cond_wait! And you shouldn't havedo_something...inside that while loop for the same reason. - user253751