我正在尝试编写一个简单的程序来使用屏障来等待多个线程的创建,然后再从主线程打印一条消息。
这是我的代码:
#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 次,但实际上只有一个线程(主线程)调用了pthread_barrier_wait
。
如果您想将主线程与工作线程同步,则需要为 NUM_WORKER_THREADS + 1 初始化屏障。
关于c++ - pthread_barrier_wait 在创建所有线程后挂起,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30941549/