pthread_join如何填充thread_result的变量

时间:2011-07-08 15:25:21

标签: c linux multithreading posix ubuntu-10.04

注意:我已删除以下代码段中的所有必需错误检查。

...
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分配空间,那么主线程必须 解除由varable持有的资源。如您所见,代码没有 包括thread_result的释放资源。所以我假设pthread_join 实际上并没有为thread_result分配空间。

现在新问题是变量thread_result如何包含没有的信息 分配任何空间?

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

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

5 个答案:

答案 0 :(得分:3)

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

事实上,发生的事情非常简单:

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

就结果而言,pthreads所做的就是将指针传递给线程边界。由应用程序决定是否以与分配方式一致的方式释放指向的内存。

答案 1 :(得分:2)

thread_result只是指向thread_function返回的数据的指针。如果thread_functionint返回void *广告,则调用pthread_join的帖子必须注意这一点并将thread_result视为int。另一方面,如果thread_function返回指向已分配内存的指针,则调用pthread_join的线程必须知道这一点并最终释放内存。

在您的示例中,thread_function返回字符串文字,thread_result将是指向字符串文字的指针。它与此相同:

 const char *str = "Hello";

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

答案 2 :(得分:2)

好吧,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. */
}

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

答案 3 :(得分:0)

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

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

在稍后的某个时候,您最终必须释放thread_result指向的内存空间。

答案 4 :(得分:0)