首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >pthread_join如何填充thread_result变量

pthread_join如何填充thread_result变量
EN

Stack Overflow用户
提问于 2011-07-08 15:25:20
回答 5查看 2.7K关注 0票数 2

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

代码语言:javascript
复制
...
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的定义。

EN

回答 5

Stack Overflow用户

回答已采纳

发布于 2011-07-08 15:29:42

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

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

  • pthread_exit由线程本身提供一个指向结果的(void*)指针;由线程决定这个指针来自何处-- from.
  • Subsequently,pthread_join --从另一个线程调用--将该指针存储在其第二个参数所指向的变量中。

就结果而言,pthreads所做的一切都是通过线程边界传递指针。应该由应用程序确保以与分配方式一致的方式解除指向内存的分配。

票数 3
EN

Stack Overflow用户

发布于 2011-07-08 15:30:12

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

在您的示例中,thread_function返回字符串文本,thread_result将是字符串文本的指针。就像这样:

代码语言:javascript
复制
 const char *str = "Hello";

字符串文字通常在数据部分中分配,所以不应该释放它们。

票数 2
EN

Stack Overflow用户

发布于 2011-07-08 15:30:28

pthread_join不分配任何东西。你的线程函数

代码语言:javascript
复制
void *thread_fun(void *arg)
{
    /* stuff */


    return something;
}

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

代码语言:javascript
复制
if (NULL != value_ptr) {
    *value_ptr = return_value; /* What you returned from your function. */
}

因此,线程函数必须分配一些内容。

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/6626685

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档