Shinforinpola
Shinforinpola

Reputation: 218

What will be the behavior of a while loop that encloses pthread_cond_wait?

I would like to know what happens with the while after a waiting thread is waked.

To avoid 'spurious wake-ups', the pthreads documentation points out that you need to use pthread_cond_wait inside a while statement.

So, when the pthread_cond_wait is called, the calling thread is blocked. And after signaled, the thread resume inside the while.

On my code, I'm handling a pthread_cond_wait() this way:

pthread_mutex_lock(&waiting_call_lock);
while(1) {
    pthread_cond_wait(&queue_cond[thread_ctx], &waiting_call_lock);
    break;
}
pthread_mutex_unlock(&waiting_call_lock);

The question is, it will try to enter the while again or somehow it break the while and go on? Or, in that case, the break after the pthread_cond_wait() is necessary?

Upvotes: 0

Views: 846

Answers (1)

Elias
Elias

Reputation: 923

To get this right, I think it is best to start with asking yourself: "what is the thread waiting for?"

The answer should not be "it should wait until another thread signals it", because the way condition variables work is assuming you have something else, some kind of mutex-protected information, that the thread is to wait for.

To illustrate this I will invent an example here where the thread is supposed to wait until a variable called counter is larger than 7. The variable counter is accessible by multiple threads and is protected by a mutex that I will call theMutex. Then the code involving the pthread_cond_wait call could look like this:

pthread_mutex_lock(&theMutex);
while(counter <= 7) {
    pthread_cond_wait(&cond, &theMutex);
}
pthread_mutex_unlock(&theMutex);

Now, if a "spurious wake-up" were to happen, the program will check the condition (counter <= 7) again and find it is still not satisfied, so it will stay in the loop and call pthread_cond_wait again. So this ensures that the thread will not proceed past the while loop until the condition is satisfied.

Since spurious wake-ups rarely happen in practice, it may be of interest to trigger that to check that your implementation works properly; here is a discussion about that: How to trigger spurious wake-up within a Linux application?

Upvotes: 2

Related Questions