2011-12-15 71 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