I could always create a status boolean that is set within the corresponding mutex, but I cannot atomically do both the set and the wait operation in one instruction, so far as I know.
That's the right way to do it -- you can do a set and wait operation atomically, because of the way condition variables interact with mutexes. When you do a pthread_cond_wait()
operation, you must have the mutex that you pass in be locked. If you correspondingly have that same mutex locked when you do a pthread_cond_signal()
, the waiting thread doesn't wake up until the signalling thread unlocks the mutex.
So, the following code would do what you want:
// Flag indicating if the worker thread is waiting or not
bool waiting = false;
...
// Worker thread code
... do stuff ...
while (!condition_is_not_satisfied())
{
pthread_mutex_lock(&mutex);
waiting = true;
pthread_cond_wait(&cond, &mutex);
waiting = false;
pthread_mutex_unlock(&mutex);
}
...
// Signalling thread code
pthread_mutex_lock(&mutex);
if (waiting)
{
// Worker thread is waiting -- signal it to wake up
pthread_cond_signal(&cond);
}
else
{
// Worker thread has not yet entered the wait state -- do something else
}
pthread_mutex_unlock(&mutex);