【问题标题】:how does pthread_join populate the variable of thread_resultpthread_join如何填充thread_result的变量
【发布时间】:2011-10-01 09:15:01
【问题描述】:

注意:我已经删除了以下 sn-p 中所有必需的错误检查。

...
void *thread_function(void *arg)
{
   ...
   pthread_exit("Hello");
}

pthread_t a_thread;
void *thread_result;

pthread_create(&a_thread, NULL, thread_function, NULL);
pthread_join(a_thread, &thread_result);
/*

int pthread_join(pthread_t th, void **thread_return);
The second argument is a pointer to a pointer that itself points to the return
value from the thread.

int pthread_exit(void *retval);
This function terminates the calling thread, returning a pointer to an object which
cannot be a local variable.

*/

问题:pthread_join如何填充thread_result的变量? 由于变量 thread_result 没有分配空间来保存信息, 如果 pthread_join 为 thread_result 分配空间,则主线程必须 释放变量持有的资源。如您所见,代码没有 包括 thread_result 的释放资源。所以我假设 pthread_join 实际上并没有为thread_result分配空间。

现在的新问题是变量 thread_result 如何在不包含信息的情况下包含信息 被分配了任何空间?

//Update-1:添加pthread_exit的定义。

//Update-2:添加thread_function的定义。

【问题讨论】:

    标签: c linux multithreading posix ubuntu-10.04


    【解决方案1】:

    thread_result 只是一个指向thread_function 返回的数据的指针。如果thread_function 返回int 转换为void *,则调用pthread_join 的线程必须意识到这一点并将thread_result 视为int。另一方面,如果thread_function 返回一个指向已分配内存的指针,则调用pthread_join 的线程必须意识到这一点并最终释放内存。

    在您的示例中,thread_function 返回字符串文字,thread_result 将是指向字符串文字的指针。和这个是一样的:

     const char *str = "Hello";
    

    字符串字面量通常分配在数据部分,因此不应释放它们。

    【讨论】:

      【解决方案2】:

      您的结论是正确的:pthread_join 没有为结果分配内存。

      其实发生的事情很简单:

      • pthread_exit 由线程本身提供了一个指向结果的 (void*) 指针;由线程决定该指针的来源。
      • 随后,pthread_join(从另一个线程调用)将该指针存储在其第二个参数指向的变量中。

      就结果而言,pthreads 所做的只是跨线程边界传递一个指针。由应用程序确保以与其分配方式一致的方式释放指向的内存。

      【讨论】:

        【解决方案3】:
        【解决方案4】:

        好吧,pthread_join 没有分配任何东西。你有你的线程函数

        void *thread_fun(void *arg)
        {
            /* stuff */
        
        
            return something;
        }
        

        然后pthread_join 出现,在它返回之前:

        if (NULL != value_ptr) {
            *value_ptr = return_value; /* What you returned from your function. */
        }
        

        所以线程函数必须分配东西。

        【讨论】:

        • 线程函数并不总是需要分配资源。例如,请查看我对 thread_function 的更新定义,它不分配资源,只是返回一个 const 字符串。
        【解决方案5】:

        好吧,thread_result 似乎被声明为一个指针。指针实际上并不需要分配空间来保存信息。该指针将指向从 pthread_join 返回的内存地址。

        更重要的是,你必须 malloc 将要在 thread_function 结束时返回的结果,否则,堆内存将会消失。

        稍后的某个时候,您最终将不得不释放 thread_result 指向的内存空间。

        【讨论】:

          猜你喜欢
          • 2011-12-29
          • 2021-02-13
          • 2016-02-19
          • 1970-01-01
          • 2014-03-25
          • 2016-05-27
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多