pthread_cond_broadcast()¶
Purpose¶
pthread_cond_broadcast() wakes all threads currently waiting on a condition variable.
It is used when a state change may allow multiple waiting threads to proceed.
Unlike pthread_cond_signal(), which wakes a single waiter, pthread_cond_broadcast() wakes every waiting thread.
Header¶
Prototype¶
Parameters¶
cond¶
Condition variable used for synchronization.
Example:
Return Value¶
Returns:
on success.
Otherwise returns a POSIX error code.
Typical Usage Pattern¶
Notifier:
pthread_mutex_lock(&lock);
shutdown_requested = true;
pthread_cond_broadcast(&cond);
pthread_mutex_unlock(&lock);
Workers:
pthread_mutex_lock(&lock);
while (!shutdown_requested)
pthread_cond_wait(&cond,
&lock);
pthread_mutex_unlock(&lock);
Behavior¶
Conceptually:
Thread A Waiting
Thread B Waiting
Thread C Waiting
↓
pthread_cond_broadcast()
↓
Wake All Waiting Threads
Each awakened thread:
Why All Threads Must Recheck¶
After wakeup:
or:
Therefore every thread must continue using:
instead of:
Example - Shutdown Notification¶
Worker thread:
pthread_mutex_lock(&lock);
while (!shutdown_requested)
pthread_cond_wait(&cond,
&lock);
pthread_mutex_unlock(&lock);
cleanup();
Controller thread:
pthread_mutex_lock(&lock);
shutdown_requested = true;
pthread_cond_broadcast(&cond);
pthread_mutex_unlock(&lock);
All workers are awakened and exit.
Example - Global State Change¶
Suppose multiple threads are waiting for:
When initialization completes:
pthread_mutex_lock(&lock);
system_ready = true;
pthread_cond_broadcast(&cond);
pthread_mutex_unlock(&lock);
All waiting threads may proceed.
broadcast() vs signal()¶
pthread_cond_signal()¶
Typical use:
pthread_cond_broadcast()¶
Typical use:
Wakeup Sequence¶
Assume:
After:
Conceptually:
However:
The awakened threads still compete for the associated mutex.
Common Mistake¶
Incorrect:
without updating the shared condition.
Awakened threads may immediately return to waiting.
Correct:
Common Mistake¶
Incorrect:
Correct:
The condition must always be rechecked.
Advantages¶
Wake All Waiters¶
Useful for global state transitions.
Simple Shutdown Handling¶
A common pattern for worker-thread termination.
Easy Coordination¶
Useful when many threads depend on the same condition.
Limitations¶
Higher Wakeup Cost¶
Many threads may wake simultaneously.
This can increase:
Potential Thundering Herd¶
Large numbers of awakened threads may compete for the same resource.