2010-12-15 31 views
0

我試圖編譯這個簡單的並行線程的程序與此命令問題而編寫並行線程編程

$ gcc -pthread -o pthreads pthreads.c 
#include <stdio.h> 
#include <pthread.h> 
#include <stdlib.h> 
#include <string.h> 
#include <errno.h> 

void *myThread(void *arg); 

int main() 
{ 
    pthread_t mythread; 
    int ret; 

    ret = pthread_create(&mythread, NULL, myThread, NULL); 

    if (ret != 0){ 
     printf("Can't create pthread: %s", strerror(errno)); 
     exit(-1); 
    } 
    return 0; 
} 

void *myThread(void *arg){ 

    // Thread code goes here.. 
    printf("OK! NOW ON THE THREAD\n"); 
    pthread_exit(NULL); 
} 

而是試圖./pthreads當沒有輸出呈現!

回答

6

您需要等待線程完成。否則,您有可能在線程開始執行之前退出。

... 
pthread_create(&mythread, NULL, myThread, NULL); 
... 
// Wait for the thread to finish. 
pthread_join(mythread, NULL); 
+0

thx男人,它現在的作品 – 2010-12-15 18:12:13

1

你沒有等你的線程完成。你需要使用pthread_join()。

1

你的問題來自於你的主線程正在從main返回,因此調用exit(或_exit)。所有正在運行的線程在程序退出時都會被終止在這種情況下,工作線程在被殺死之前沒有時間執行。

您可以使用pthread_join在從main返回之前等待線程的完成。

#include <stdio.h> 
#include <pthread.h> 
#include <stdlib.h> 
#include <string.h> 
#include <errno.h> 

void *myThread(void *arg); 

int main() 
{ 
    void* thread_return; 
    pthread_t mythread; 
    int ret; 

    ret = pthread_create(&mythread, NULL, myThread, NULL); 
    if (ret != 0) 
    { 
     printf("Can't create pthread: %s\n", strerror(errno)); 
     exit(-1); 
    } 

    ret = pthread_join(mythread, &thread_return); 
    if (ret != 0) 
    { 
     printf("Can't join pthread: %s\n", strerror(errno)); 
     exit(-1); 
    } 

    return 0; 
} 

void *myThread(void *arg) 
{ 
    printf("OK! NOW ON THE THREAD\n"); 
    pthread_exit(NULL); 
} 
1

Sanjit的答案當然是正確的,但對擴大你的線程工具箱的緣故,您也可能看pthread_barrier_wait。當你有一個簡單的程序有很多線程和main看起來像「開始所有工作線程並等待它們完成」,讓主要和所有工作人員簡單地等待障礙可以是一個很好的方法來避免必須存儲所有工作線程ID並將它們加入for循環。障礙還有許多其他的巧妙用途,有時可以避免用互斥鎖和條件變量做同樣的事情帶來不必要的複雜性。

+0

thx男人爲此 – 2010-12-15 20:09:49