Pthread barrier example - simulate work then wait at barrier

pthread-barrier-simulate-work.c
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <pthread.h>
 
#define NUM_THREADS 5  // Number of threads
 
// Barrier variable
pthread_barrier_t barrier;
 
// Function executed by each thread
void *thread_work(void *tid) {
    long my_tid = (long)tid;
    printf("Thread %ld is doing some work before the barrier\n", my_tid);
 
    // Simulate some work
    sleep(1); // Sleep for a second to simulate work
 
    // Wait at the barrier
    printf("Thread %ld is waiting at the barrier\n", my_tid);
    pthread_barrier_wait(&barrier);
 
    printf("Thread %ld passed the barrier\n", my_tid);
    pthread_exit(NULL);
}
 
int main() {
    pthread_t threads[NUM_THREADS];
    int status;
 
    // Initialize the barrier
    pthread_barrier_init(&barrier, NULL, NUM_THREADS);
 
    // Create threads
    for(long i = 0; i < NUM_THREADS; i++) {
        printf("In main: creating thread %ld\n", i);
        status = pthread_create(&threads[i], NULL, thread_work, (void *)i);
 
        if (status) {
            printf("ERROR; return code from pthread_create() is %d\n", status);
            exit(-1);
        }
    }
 
    // Wait for all threads to complete
    for(int i = 0; i < NUM_THREADS; i++) {
        pthread_join(threads[i], NULL);
    }
 
    // Destroy the barrier
    pthread_barrier_destroy(&barrier);
 
    printf("Main: program completed.\n");
    return 0;
}

This program demonstrates the use of a pthread barrier for synchronizing threads.
It creates a specified number of threads, each performing some “work” (simulated with sleep) and then waiting at a barrier.

The barrier ensures that no thread proceeds until all threads have reached the barrier.

Barrier Initialization: pthread_barrier_init initializes the barrier and sets the count to NUM_THREADS, so the barrier knows how many threads to expect.

Thread Creation: The program creates NUM_THREADS threads, each executing the thread_work function.

Thread Function: Each thread simulates doing work, prints a message when it reaches the barrier, and waits for other threads using pthread_barrier_wait.

Main Function: After creating all threads, the main function waits for them to complete, then destroys the barrier and concludes.