我正在尝试编写一个简单的程序,在从main打印消息之前使用屏障等待创建多个线程。
这是我的代码:
#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;
}
目前,我的程序打印了一些非确定性的“Hello from thread”语句,并在打印“Hello from main!”之前挂起;但是,它总是打印8个线程消息。因此,创建了所有线程。
为什么还挂着?
屏障期望在NUM_THREADS次上进行wait
ed,但只有一个主线程实际调用pthread_barrier_wait
。
如果要将main与工作线程同步,则需要初始化NUM_WORKER_THREADS + 1的屏障。