pthread_cond_wait()¶
Purpose¶
pthread_cond_wait() suspends the calling thread until a condition variable is signaled.
It is typically used together with a mutex to implement event-driven synchronization between threads.
The function atomically:
This atomic behavior prevents missed wakeup races.
Header¶
Prototype¶
Parameters¶
cond¶
Condition variable used for waiting.
Example:
mutex¶
Mutex protecting the shared condition.
Example:
Return Value¶
Returns:
on success.
Otherwise returns a POSIX error code.
Typical Usage Pattern¶
pthread_mutex_lock(&lock);
while (!condition) {
pthread_cond_wait(&cond,
&lock);
}
pthread_mutex_unlock(&lock);
Why Use a While Loop?¶
Incorrect:
Correct:
Reason¶
A waiting thread may wake up because of:
or:
or:
Therefore the condition must always be rechecked.
Internal Behavior¶
Conceptually:
Another thread:
Waiting thread:
Producer-Consumer Example¶
Consumer:
pthread_mutex_lock(&lock);
while (queue_empty())
pthread_cond_wait(&cond,
&lock);
item = queue_pop();
pthread_mutex_unlock(&lock);
Producer:
pthread_mutex_lock(&lock);
queue_push(item);
pthread_cond_signal(&cond);
pthread_mutex_unlock(&lock);
Why Mutex Is Required¶
The condition variable itself does not protect shared data.
Incorrect:
The condition must be protected by a mutex.
Correct:
pthread_mutex_lock(&lock);
while (!condition)
pthread_cond_wait(&cond,
&lock);
pthread_mutex_unlock(&lock);
Common Mistake¶
Incorrect:
pthread_mutex_lock(&lock);
if (!condition)
pthread_cond_wait(&cond,
&lock);
pthread_mutex_unlock(&lock);
Using:
instead of:
may lead to incorrect behavior.
Common Mistake¶
Incorrect:
without holding the mutex.
This may introduce race conditions.
Advantages¶
Efficient Waiting¶
Threads sleep instead of busy-waiting.
Event Driven¶
Ideal for:
Limitations¶
Requires Mutex¶
Condition variables must be used together with a mutex.
Predicate Required¶
A condition variable does not store state.
The program must maintain a shared predicate.
Example: