【问题标题】:pthread_join() and pthread_exit()pthread_join() 和 pthread_exit()
【发布时间】:2012-01-20 18:47:47
【问题描述】:

我有一个关于 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 指针?我的意思是基本上它们都是线程的返回值,为什么类型不同?

【问题讨论】:

    标签: c multithreading concurrency pthreads


    【解决方案1】:

    因为每次

    void pthread_exit(void *ret);
    

    将从线程函数中调用,因此无论您想要返回哪个指针,都只需使用 pthread_exit() 传递。

    现在

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

    将始终从创建线程的位置调用,因此在这里接受返回的指针,您需要 双指针 ..

    我认为这段代码会帮助你理解这一点

    #include <stdio.h>
    #include <string.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\n",b); 
        free(b); // lets free the memory
    
    }
    

    【讨论】:

    • 如果它在 main() 中,为什么你必须 free(b)?这是因为您在堆上分配了 a 吗?
    【解决方案2】:

    pthread_exit中,ret是一个输入参数。您只是将变量的地址传递给函数。

    pthread_join 中,ret 是一个输出参数。你从函数中取回一个值。例如,可以将此类值设置为NULL

    详细解释:

    pthread_join 中,您会取回已完成线程传递给pthread_exit 的地址。如果您只传递一个普通指针,它是按值传递的,因此您无法更改它指向的位置。为了能够改变传递给pthread_join的指针的值,必须将其作为指针本身传递,即指向指针的指针。

    【讨论】:

    • 但是为什么要在pthread_exit 中定义一个void * 类型的ret,它总是NULL 或其他一些常量值
    【解决方案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
    

    【讨论】:

      猜你喜欢
      • 2015-01-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-06-16
      • 1970-01-01
      • 1970-01-01
      • 2014-01-16
      相关资源
      最近更新 更多