2015-06-19 28 views
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

+0

你忽略其中'threadFun'在屏障等待的一部分嗎? – pilcrow

+0

@pilcrow我在'threadFun'的'printf'之前加了一個'pthread_barrier_wait(&barrier)',但它仍然掛起。這次我看到「主從你好!」後面是* 7 *「來自線程的Hello」語句。 – erip

+0

如果您希望屏障等待您的8個工作線程*和*爲主線程,則需要爲9個線程設置屏障,而不是8個線程(並且所有線程都需要等待屏障,但它聽起來像就像你已經做出了這樣的改變)。 –

回答

2

阻隔預計將wait版上NUM_THREADS次,但只有一個線程,主線程,實際上調用pthread_barrier_wait

如果您要同步主與你的工作線程,你需要初始化NUM_WORKER_THREADS阻隔+ 1

+0

這工作。很酷。 – erip

相關問題