
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

#define NUM_THREADS 5

pthread_barrier_t barrier;

void* thread_work(void* arg) {
    long id = (long)arg;
    
    printf("Thread %ld: Doing first phase of work...\n", id);
    sleep(id + 1); // Simulate distinct work durations
    
    printf("Thread %ld: Reached the barrier.\n", id);
    pthread_barrier_wait(&barrier); // Wait for all threads to arrive
    
    // All threads unblock simultaneously here
    printf("Thread %ld: Passed the barrier! Starting second phase.\n", id);
    
    return NULL;
}

int main() {
    pthread_t threads[NUM_THREADS];
    
    // Initialize the barrier for NUM_THREADS
    pthread_barrier_init(&barrier, NULL, NUM_THREADS);
    
    // Create threads
    for (long i = 0; i < NUM_THREADS; i++) {
        pthread_create(&threads[i], NULL, thread_work, (void*)i);
    }
    
    // Wait for all threads to finish
    for (int i = 0; i < NUM_THREADS; i++) {
        pthread_join(threads[i], NULL);
    }
    
    // Destroy the barrier
    pthread_barrier_destroy(&barrier);
    printf("All threads finished. Program exiting.\n");
    
    return 0;
}

