2011-12-15 67 views
35

我有一個關於C併發編程的問題。pthread_join()和pthread_exit()

在並行線程庫的pthread_join原型是

int pthread_join(pthread_t tid, void **ret); 

pthread_exit的原型爲:

void pthread_exit(void *ret); 

所以我感到困惑的是,爲什麼pthread_join需要過程的返回值作爲指向void指針的指針,但pthread_exit僅需要void來自退出線程的指針?我的意思是基本上它們都是來自線程的返回值,爲什麼類型有差異?

回答

32

pthread_exitret是一個輸入參數。您只是將變量的地址傳遞給函數。

pthread_joinret是輸出參數。你從函數中取回一個值。例如,此值可以設置爲NULL

朗解釋:

pthread_join,你回來的成品線程傳遞給pthread_exit地址。如果僅傳遞一個普通指針,它將按值傳遞,因此您無法更改它指向的位置。爲了能夠改變傳遞給pthread_join的指針的值,它必須作爲指針本身傳遞,也就是指向指針的指針。

+0

但是爲什麼在`pthread_exit`中定義一個`void *`類型,它總是`NULL`或者其他一些常量值 – stonestrong 2014-02-13 08:22:37

3

典型的使用是

void* ret = NULL; 
pthread_t tid = something; /// change it suitably 
if (pthread_join (tid, &ret)) 
    handle_error(); 
// do something with the return value ret 
25

這是因爲每一次

void pthread_exit(void *ret); 

將從所以它永遠要簡單地返回其指針傳遞用了pthread_exit()線程函數被調用。

現在在

int pthread_join(pthread_t tid, void **ret); 

將從創建線程地方所以在這裏接受返回的指針總是叫你需要雙指針 ..

我認爲這個代碼將幫助你瞭解這個

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

void* thread_function(void) 
{ 
    char *a = malloc(10); 
    strcpy(a,"hello world"); 
    pthread_exit((void*)a); 
} 
int main() 
{ 
    pthread_t thread_id; 
    char *b; 

    pthread_create (&thread_id, NULL,&thread_function, NULL); 

    pthread_join(thread_id,(void**)&b); //here we are reciving one pointer 
             value so to use that we need double pointer 
    printf("b is %s",b); 
    free(b); // lets free the memory 

} 
+5

內存泄漏.... – gliderkite 2014-03-05 18:36:14