Condition variables are divided into two parts: Condition and variable. The condition itself is protected by mutex. The thread must lock the mutex before changing the condition state.
1. Initialization:
The data type used by the condition variable is pthread_cond_t. Initialization is required before use. Two methods are available:
- Static: the constant pthread_cond_initializer can be assigned to the static conditional variable.
- Dynamic: The pthread_cond_init function is used to clean up the memory space of the dynamic condition variable before it is released.
# Include < Pthread. h >
Int Pthread_cond_init (pthread_cond_t * Restrict cond, pthread_condattr_t * Restrict ATTR );
Int Pthread_cond_destroy (pthread_cond_t * Cond );
If the call succeeds, 0 is returned. If the call fails, the error number is returned.
When the ATTR parameter of pthread_cond_init is null, a conditional variable of the default attribute will be created. It will be discussed after non-default conditions.
2. Waiting conditions:
# Include < Pthread. h >
Int Pthread_cond_wait (pthread_cond_t * Restrict cond, pthread_mutex_t * Restric mutex );
Int Pthread_cond_timedwait (pthread_cond_t * Restrict cond, pthread_mutex_t * Restrict mutex, Const Struct Timespec * Restrict timeout );
If the call succeeds, 0 is returned. If the call fails, the error number is returned.
These two functions are respectively blocked wait and timeout wait.
The wait condition function waits for the condition to become true. The mutex passed to pthread_cond_wait protects the condition. The caller passes the locked mutex to the function. the function places the call thread on the list of threads waiting for the condition, and then unlocks the mutex. These two operations are atomic. in this way, the time channel between the condition check and the thread entering the sleep state waiting for the condition to change the two operations is closed, so that the thread will not miss any change in the condition.
When pthread_cond_wait returns, the mutex is locked again.
3. Notification conditions:
# Include < Pthread. h >
Int Pthread_cond_signal (pthread_cond_t * Cond );
Int Pthread_cond_broadcast (pthread_cond_t * Cond );
If the call succeeds, 0 is returned. If the call fails, the error number is returned.
These two functions are used to notify the thread that the condition has been met. call these two functions, also known as sending signals to the thread or condition. You must note that you must send signals to the thread after changing the condition state.