Broadcasting to all threads
What you'll learn: How to wake up every waiting thread at once using the pthread_cond_broadcast function.
The "Check Again" Alarm
In multithreaded programming, we often use pthread_cond_wait to put a thread to sleep until a specific condition is met. Usually, we wake these threads up using pthread_cond_signal. However, signal only wakes up one waiting thread. If you have ten threads waiting for a "Go!" signal and you use signal, nine of them will keep sleeping while the winner starts working.
Think of it like a group of people waiting for a bus. If the bus driver only opens the front door and says "I have room for one person," that’s a signal. But if the driver shouts "The bus is here, everyone get in line!", that’s a broadcast.
When to Broadcast
You use pthread_cond_broadcast when a state change in your program might be relevant to every single thread currently waiting. Common scenarios include:
- A "Start" Trigger: You have 50 worker threads initialized and ready, but they must wait for a "Go" signal from the main thread.
- Resource Availability: A shared pool of memory was empty, and now a large chunk has been freed—enough for multiple threads to use.
- Shutting Down: You want all threads to wake up, see a "shutdown" flag, and exit gracefully.
Coding the Broadcast
Instead of calling signal in a loop, you call broadcast once. All waiting threads move from the "waiting" state back to the "ready" state. They will then fight for the mutex lock one by one to proceed.
#include <pthread.h>
#include <stdio.h>
pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
int ready_to_start = 0;
void* worker(void* arg) {
pthread_mutex_lock(&lock);
// Threads sleep here until ready_to_start is 1
while (!ready_to_start) {
pthread_cond_wait(&cond, &lock);
}
printf("Thread %ld is now running!\n", (long)arg);
pthread_mutex_unlock(&lock);
return NULL;
}
int main() {
pthread_t threads[5];
for (long i = 0; i < 5; i++) pthread_create(&threads[i], NULL, worker, (void*)i);
// Simulate some preparation work...
pthread_mutex_lock(&lock);
ready_to_start = 1;
// Wake up EVERYONE at once
pthread_cond_broadcast(&cond);
pthread_mutex_unlock(&lock);
for (int i = 0; i < 5; i++) pthread_join(threads[i], NULL);
return 0;
}
Key takeaway
Use pthread_cond_broadcast when a change in state allows multiple threads to make progress simultaneously.