pthread_join()和pthread_exit()

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_exitvoid从指定的线程获取指针?我的意思是基本上它们都是来自线程的返回值,为什么类型有差异?

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)