I'm trying to write a simple program to use a barrier to wait for the creation of several threads before printing a message from the main.
Here's my code:
#include <iostream>
#include <pthread.h>
#include <stdio.h>
#include <cstdlib>
#include <cstdint>
#define NUM_THREADS 8
pthread_barrier_t barrier;
void *threadFun(void *tid)
{
intptr_t temp = (intptr_t) tid;
printf("Hello from thread %d\n", temp);
}
int main()
{
pthread_t threads[NUM_THREADS];
int rc;
pthread_barrier_init(&barrier, NULL, NUM_THREADS);
for(int i = 0; i < NUM_THREADS; ++i) {
rc = pthread_create(&threads[i], NULL, threadFun, (void *) i);
if(rc) {
printf("Error creating thread %d\n", i);
exit(-1);
}
}
pthread_barrier_wait(&barrier);
printf("Hello from main!\n");
for(int i = 0; i < NUM_THREADS; ++i) {
pthread_join(threads[i], NULL);
}
pthread_barrier_destroy(&barrier);
return 0;
}
Currently, my program prints some non-deterministic assortment of "Hello from thread " statements, and hangs before printing "Hello from main!"; however, it always prints 8 thread messages. Thus, all the threads are created.
Why is it still hanging?
The barrier expects to be
wait
ed on NUM_THREADS times, but only one thread, the main thread, actually callspthread_barrier_wait
.If you want to synchronize main with your worker threads, you'll need to initialize the barrier for NUM_WORKER_THREADS + 1.