2
我正试图编写一个简单的程序来使用屏障来等待几个线程的创建,然后再打印主消息。pthread_barrier_wait在所有线程创建后挂起
这里是我的代码:
#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;
}
目前,我的程序将打印的“你好,从线程”陈述一些非确定性的品种,并在打印前挂起“;从主你好!”但是,它总是打印8个线程消息。因此,所有的线程都被创建。
为什么它仍然悬挂?
感谢, erip
你忽略其中'threadFun'在屏障等待的一部分吗? – pilcrow
@pilcrow我在'threadFun'的'printf'之前加了一个'pthread_barrier_wait(&barrier)',但它仍然挂起。这次我看到“主从你好!”后面是* 7 *“来自线程的Hello”语句。 – erip
如果您希望屏障等待您的8个工作线程*和*为主线程,则需要为9个线程设置屏障,而不是8个线程(并且所有线程都需要等待屏障,但它听起来像就像你已经做出了这样的改变)。 –