![]() |
![]() |
![]() |
Wait on condition variable
#include <pthread.h> int pthread_cond_wait( pthread_cond_t* cond, pthread_mutex_t* mutex );
libc
The pthread_cond_wait() function blocks the calling thread on the condition variable cond, and unlocks the associated mutex mutex. The calling thread must have locked mutex before waiting on the condition variable. Upon return from the function the mutex is again locked and owned by the calling thread.
The calling thread is blocked until either another thread performs a signal or broadcast on the condition variable, a signal is delivered to the thread, or the thread is canceled (waiting on a condition variable is a cancellation point). In all cases the thread reacquires the mutex before being unblocked.
![]() |
You shouldn't use a recursive mutex with condition variables. |
This example shows how condition variables can be used to synchronize producer and consumer threads.
#include <stdio.h> #include <pthread.h> pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t cond = PTHREAD_COND_INITIALIZER; int condition = 0; int count = 0; int consume( void ) { while( 1 ) { pthread_mutex_lock( &mutex ); while( condition == 0 ) pthread_cond_wait( &cond, &mutex ); printf( "Consumed %d\n", count ); condition = 0; pthread_cond_signal( &cond ); pthread_mutex_unlock( &mutex ); } return( 0 ); } void* produce( void * arg ) { while( 1 ) { pthread_mutex_lock( &mutex ); while( condition == 1 ) pthread_cond_wait( &cond, &mutex ); printf( "Produced %d\n", count++ ); condition = 1; pthread_cond_signal( &cond ); pthread_mutex_unlock( &mutex ); } return( 0 ); } int main( void ) { pthread_create( NULL, NULL, &produce, NULL ); return consume(); }
Safety: | |
---|---|
Cancellation point | Yes |
Interrupt handler | No |
Signal handler | Yes |
Thread | Yes |
pthread_cond_broadcast(), pthread_cond_init(), pthread_cond_signal(), pthread_cond_timedwait(), SyncCondvarWait()
![]() |
![]() |
![]() |