2016-05-22 32 views
0

喜同胞程序員,Ç - 在pthread_join()掛起(有時)

我想用C寫一個簡單的多線程程序與並行線程,但不知何故在pthread_join似乎掛起。 它似乎並不總是,有時一切運行良好,下次不掛,通常在第一個線程。

我已經儘量減少代碼到最低限度,這樣我就可以排除其他問題。當然,在完整的代碼中,線程做了一些計算。但即使使用這種非常簡化的代碼,問題仍然存在。在多臺機器上,使用不同的操作系統。

strace的向我表明掛有事情做了FUTEX_WAIT,全最後幾行:

write(1, "Joining Thread 0...\n", 20Joining Thread 0... 
) = 20 
futex(0x7fff61718a20, FUTEX_WAIT, 1634835878, NULL 

我嘗試使用gdb調試它,但我那可憐的調試劇照非常有限,尤其是多線程化程序。 我也嘗試使用不同的C標準(C99和Ansi)和兩個pthread參數(-lpthread,-pthread)來編譯它,但問題仍然存在。

的(降低的)碼monte2.c:

#include <stdio.h> 
#include <pthread.h> 

void *monte(struct MonteArgs *args) { 
    pthread_exit(NULL); 
} 

int main(int argc, char **argv) { 

    int numThreads, numSamples; 
    int i; 

    if (argc != 3) { 
    printf("Usage: monte threads samples\n"); 
    exit(1); 
    } 

    numThreads = atoi(argv[1]); 
    pthread_t threads[numThreads]; 
    numSamples = atoi(argv[2]); 

    for (i=0; i<numThreads; i++) { 
    if (pthread_create(&threads[i], NULL, monte, NULL)) { 
     printf("Error Creating Thread %d!\n", i); 
     return 1; 
    } 
    } 

    for (i=0; i<numThreads; i++){ 
    printf("Joining Thread %d...\n", i); 
    pthread_join(&threads[i], NULL); 
    } 

    printf("End!\n"); 
    fflush(stdout); 
    return(0); 
} 

予編譯

gcc monte2.c -lpthread -o monte 

並用

./monte2 3 100 

其中第一個參數是線程數運行,而第二個實際上並不需要簡化的代碼。

+0

你想使用PTreads編譯代碼時加上'-pthread'。 – alk

回答

3

自從我完成了多線程C以來已經有一段時間了,但是您不應該忽略編譯器警告:-)。編譯-Wall

你應該會看到一個警告是這樣的:

note: expected 'pthread_t' but argument is of type 'pthread_t *' 
int  WINPTHREAD_API pthread_join(pthread_t t, void **res); 

你傳遞一個pthread_t*時,你應該通過pthread_t

參考pthread_join文檔:http://man7.org/linux/man-pages/man3/pthread_join.3.html

+0

謝謝你! :-)這個簡單的東西解決了它。我發現它並不總是這樣,我感覺很奇怪,我只是沒有看到它,因爲我用其他簡單的例子交叉檢查了我的簡化程序,他們通常這樣做。 。 – juks