pthread_cond_signal()¶
Purpose¶
pthread_cond_signal() wakes one thread currently waiting on a condition variable.
It is typically used to notify a single waiting thread that a shared condition may have changed.
Header¶
Prototype¶
Parameters¶
cond¶
Condition variable used for synchronization.
Example:
Return Value¶
Returns:
on success.
Otherwise returns a POSIX error code.
Typical Usage Pattern¶
Producer:
pthread_mutex_lock(&lock);
condition = true;
pthread_cond_signal(&cond);
pthread_mutex_unlock(&lock);
Consumer:
pthread_mutex_lock(&lock);
while (!condition)
pthread_cond_wait(&cond,
&lock);
pthread_mutex_unlock(&lock);
Behavior¶
Conceptually:
Another thread:
The awakened thread:
One Thread Is Woken¶
If multiple threads are waiting:
then:
wakes:
The specific thread selected is implementation-dependent.
Producer-Consumer Example¶
Producer:
pthread_mutex_lock(&lock);
queue_push(item);
pthread_cond_signal(&cond);
pthread_mutex_unlock(&lock);
Consumer:
pthread_mutex_lock(&lock);
while (queue_empty())
pthread_cond_wait(&cond,
&lock);
item = queue_pop();
pthread_mutex_unlock(&lock);
Why Signal While Holding Mutex?¶
Recommended pattern:
pthread_mutex_lock(&lock);
condition = true;
pthread_cond_signal(&cond);
pthread_mutex_unlock(&lock);
This ensures:
occurs in a well-defined order.
Signal Does Not Store State¶
A condition variable is not an event queue.
Incorrect assumption:
This is false.
Condition variables only notify threads that are already waiting.
The shared condition must always be checked separately.
Common Mistake¶
Incorrect:
without updating the associated condition.
A waiting thread may wake up and immediately go back to sleep.
Correct:
Common Mistake¶
Incorrect:
The waiting thread must still use:
because wakeup does not guarantee the condition remains true.
signal() vs broadcast()¶
pthread_cond_signal()¶
Best for:
pthread_cond_broadcast()¶
Best for:
Advantages¶
Efficient¶
Only one waiting thread is awakened.
Low Wakeup Overhead¶
Avoids unnecessary context switches.
Limitations¶
May Not Wake Desired Thread¶
The implementation chooses which waiting thread receives the wakeup.
Requires Shared Predicate¶
Condition variables do not maintain state themselves.
The application must maintain:
or similar predicates.