Search code examples
multithreadingpthreadsmutexcondition-variable

What happens to a thread calling pthread_cond_signal?


When a thread calls pthread_cond_signal, one of the threads waiting on the condition will resume its execution. But what happens to the calling thread? Does it waits for the called thread to release the mutex and then it resumes?

For example, the waiting thread:

pthread_mutex_lock(&mut);
// ...
pthread_cond_wait(&cond, &mut);
// ...
pthread_mutex_unlock(&mut);

And the signaling thread:

pthread_mutex_lock(&mut);
// ...
pthread_cond_signal(&cond);
// ... has work to finish
pthread_mutex_unlock(&mut);

In this case, how can the signaling thread continue its work if the waiting thread has taken over the mutex?


Solution

  • The thread that calls pthread_cond_signal returns immediately. It does not wait for the woken thread (if there is one) to do anything.

    If you call pthread_cond_signal while holding the mutex that the blocked thread is using with pthread_cond_wait, then the blocked thread will potentially wake from the condition variable wait, then immediately block waiting for the mutex to be acquired, since the signalling thread still holds the lock.

    For the best performance, you should unlock the mutex prior to calling pthread_cond_signal.

    Also, pthread_cond_wait may return even though no thread has signalled the condition variable. This is called a "spurious wake". You typically need to use pthread_cond_wait in a loop:

    pthread_mutex_lock(&mut);
    while(!ready){
        pthread_cond_wait(&cond,&mut);
    }
    // do stuff
    pthread_mutex_unlock(&mut);
    

    The signalling thread then sets the flag before signalling:

    pthread_mutex_lock(&mut);
    ready=1
    pthread_mutex_unlock(&mut);
    pthread_cond_signal(&cond);