Search code examples
cpthreadssignalssystems-programming

pthread_cond_wait blocks(sleeps) indefinitely until pthread_cond_signal is called by another thread in C?


If a thread: A is blocked in pthread_cond_wait for a condition, will our thread A will be sleeping indefinitely waiting for pthread_cond_signal being called in another thread? Or it will be woken up even when the condition somehow becomes true (workload > MAXLOAD ) without being signaled using pthread_cond_wait.

Thread A:

while(1) {
    pthread_mutex_lock( &recoveryMutex );  
    while( workload < MAXLOAD ) {                               
        pthread_cond_wait(&recoveryCond, &recoveryMutex );      
    }
    /* Recovery Code */
    /* Recovery Code */
    /* Recovery Code */        
    pthread_mutex_unlock(&recoveryMutex);
}

Solution

  • In short, yes, it block/sleeps indefinitely until you signal it.

    pthread_cond_wait may wake "spuriously" for any reason (which would generally not have any relation to the condition becoming true; mechanically there's no reasonable way such a relation could come to be), but has no contract to wake until pthread_cond_signal or pthread_cond_broadcast has been called. You need to call one of these functions whenever you've made some change in state that could cause the truth value of the predicate to change.