我对C并发编程有疑问。
在pthread库中,pthread_join
的原型是
int pthread_join(pthread_t tid, void **ret);
和pthread_exit
的原型是:
void pthread_exit(void *ret);
所以我很困惑,为什么pthread_join
将进程的返回值作为指向来自收到线程的void
指针的指针,但是pthread_exit
只需要void
来自退出线程的指针?我的意思是基本上它们都是来自线程的返回值,为什么类型有差异?
答案 0 :(得分:40)
在pthread_exit
中,ret
是输入参数。您只是将变量的地址传递给函数。
在pthread_join
中,ret
是输出参数。你从函数中找回一个值。例如,可以将此值设置为NULL
。
冗长的解释:
在pthread_join
中,您将获得完成的线程传递给pthread_exit
的地址。如果只传递一个普通指针,它将按值传递,因此您无法更改指向的位置。为了能够更改传递给pthread_join的指针的值,它必须作为指针本身传递,即指向指针的指针。
答案 1 :(得分:31)
因为每次都是
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 *ignoredInThisExample)
{
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
}
答案 2 :(得分: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