In my C++ program I have a class CEvent with trigger and wait member functions based on pthreads (running on Linux). Implementation is quite obvious (i.e. many examples online) if there is one waiting process. However now I need to satisfy the requirement that multiple threads are waiting on the event and should ALL wake up reliably when trigger() is called. As a second condition, only threads that were waiting when trigger() was called should wake up.
My current code:
void CEvent::trigger() {
pthread_mutex_lock(&mutex);
wakeUp = true;
pthread_cond_broadcast(&condition)
pthread_mutex_unlock(&mutex);
wakeUp = false;
}
void CEvent::wait() {
pthread_mutex_lock(&mutex);
while (!wakeUp)
pthread_cond_wait(&condition, &mutex)
pthread_mutex_unlock(&mutex);
}
This seems to almost work, insofar as that all threads waiting wake up before I set wakeUp back to false. However between the broadcast and the reset of wakeUp, other (or the same) threads calling wait() will also wake up right away which is not acceptable. Putting wakeUp = false before the mutext unlocking prevents the threads from waking up.
My questions: * When does pthread_cond_broadcast return? I.e. is there a guarantee it will only return after all threads have woken up or could it return before? * Are there any recommended solutions to this problem?