All*_*ang 41 c concurrency multithreading pthreads
我有一个关于C并发编程的问题.
在pthread库中,原型pthread_join
是
int pthread_join(pthread_t tid, void **ret);
Run Code Online (Sandbox Code Playgroud)
原型pthread_exit
是:
void pthread_exit(void *ret);
Run Code Online (Sandbox Code Playgroud)
所以我很困惑,为什么pthread_join
将进程的返回值作为void
指向收到线程的指针的指针,但pthread_exit
只void
从指定的线程获取指针?我的意思是基本上它们都是来自线程的返回值,为什么类型有差异?
ste*_*anB 39
In pthread_exit
,ret
是输入参数.您只是将变量的地址传递给函数.
In pthread_join
,ret
是输出参数.你从函数中找回一个值.例如,可以将此值设置为NULL
.
很长的解释:
在pthread_join
,你得到pthread_exit
完成的线程传递给的地址.如果只传递一个普通指针,它将按值传递,因此您无法更改它指向的位置.为了能够更改传递给pthread_join的指针的值,它必须作为指针本身传递,即指向指针的指针.
Jee*_*tel 31
这是因为每一次
void pthread_exit(void *ret);
Run Code Online (Sandbox Code Playgroud)
将从线程函数调用,所以你想要返回它的指针传递与pthread_exit().
现在在
int pthread_join(pthread_t tid, void **ret);
Run Code Online (Sandbox Code Playgroud)
将始终从创建线程的地方调用,所以这里接受返回的指针,你需要双指针 ..
我认为这段代码可以帮助您理解这一点
#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
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
104695 次 |
最近记录: |