2011-06-24 47 views
0

我想學習Unix C併爲練習做一些練習。我正在處理的當前問題涉及POSIX線程(主要是pthread_create()和pthread_join())posix線程(pthread_create和pthread_join)

該問題要求使用兩個線程重複打印「Hello World」。一個線程打印「Hello」1000次,而第二個線程打印「World」1000次。主程序/線程將在繼續之前等待兩個線程完成。

這是我現在所擁有的。

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

void *print_hello(void *arg) 
{ 
    int iCount; 
    for(iCount = 0; iCount < 1000; iCount++) 
    { 
    printf("Hello\n"); 
    } 
} 

void *print_world(void *arg) 
{ 
    int iCount; 
    for(iCount = 0; iCount < 1000; iCount++) 
    { 
     printf("World\n"); 
    } 
} 

int main(void) 
{ 
    /* int status; */ 
    pthread_t thread1; 
    pthread_t thread2; 

    pthread_create(&thread1, NULL, print_hello, (void*)0); 
    pthread_create(&thread2, NULL, print_world, (void*)0); 

    pthread_join(thread1, NULL); 
    pthread_join(thread2, NULL); 

    return 0; 
} 

這似乎沒有充分發揮作用。它按預期打印「你好」。但「世界」根本沒有印。似乎第二個線程根本沒有運行。不知道我正在使用pthread_join。正如練習所要求的,我的意圖是讓主線程「等待」這兩個線程。

任何幫助,將不勝感激。

+0

似乎對我很好,並按預期工作。你可能想在你的線程函數的最後加上'return NULL'。 – JackOfAllTrades

+0

要評論你的代碼,NULL通常被定義爲「(void *)0」,所以它有點愚蠢的使用兩者。我建議NULL - 不保證所有系統上的空指針都被表示爲0,而NULL將被定義爲適當的值。 –

回答

7

是什麼讓你覺得它沒有運行兩個線程?我認爲輸出結果只是尖叫過去,你很快就會注意到 - 你將在一個塊中獲得大量的每個線程的輸出。

嘗試將輸出重定向到文件並查看實際打印的內容。

2

我剛剛運行您的代碼。

$ gcc ./foo.c -pthread 
$ ./a.out | grep World | wc -l 
1000 
$ ./a.out | grep Hello | wc -l 
1000 

適用於Ubuntu 10.10和gcc-4.5.2。仔細檢查你的編譯和你的輸出。