Thread barriers
What you'll learn: How to synchronize multiple threads so they all wait for one another at a specific checkpoint before proceeding.
The "All-or-Nothing" Wait
Imagine you are going out for dinner with four friends. You all drive separate cars. Even if you arrive at the restaurant first, you can't be seated until the entire group is present. You wait by the door. As each friend arrives, the group grows, but no one enters the dining room yet. Only when the final person pulls into the parking lot does the whole group move inside together.
In systems programming, a barrier is that restaurant door. It is a synchronization primitive used when a task is split into phases. No thread can start "Phase 2" until every single thread has finished "Phase 1."
Implementing a Barrier
In POSIX threads (pthreads), we use pthread_barrier_t. You initialize it by specifying how many threads it should wait for. When a thread reaches the checkpoint, it calls pthread_barrier_wait().
If the count is set to 5, the first four threads to call this function will fall asleep (block). The moment the 5th thread calls it, the barrier "trips," and all five threads are woken up simultaneously to continue their work.
#include <pthread.h>
pthread_barrier_t my_barrier;
void* worker(void* arg) {
// Phase 1: Heavy calculation
do_expensive_setup();
// Wait here! Nobody passes until everyone arrives.
pthread_barrier_wait(&my_barrier);
// Phase 2: Use results from everyone's Phase 1
do_combined_work();
return NULL;
}
int main() {
// Initialize barrier for 3 threads
pthread_barrier_init(&my_barrier, NULL, 3);
// ... start 3 threads ...
pthread_barrier_destroy(&my_barrier);
return 0;
}
Why use them?
Barriers are essential for parallel algorithms where one step depends on the completed results of all previous steps. For example, if you are processing a large image in chunks across four CPU cores, you might need a barrier after a "blur" pass to ensure the entire image is finished before you start a "sharpen" pass. Without the barrier, one fast thread might start sharpening pixels that haven't been blurred yet, leading to corrupted data.
Key takeaway
A barrier forces a group of threads to stop and wait until every thread in that group has reached the same point in the code.