注意:我已经删除了以下代码段中所有必需的错误检查。
...
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的定义。
发布于 2011-07-08 15:29:42
您的结论是正确的:pthread_join没有为结果分配内存。
事实上,发生的事情非常简单:
pthread_exit由线程本身提供一个指向结果的(void*)指针;由线程决定这个指针来自何处-- from.pthread_join --从另一个线程调用--将该指针存储在其第二个参数所指向的变量中。就结果而言,pthreads所做的一切都是通过线程边界传递指针。应该由应用程序确保以与分配方式一致的方式解除指向内存的分配。
发布于 2011-07-08 15:30:12
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";字符串文字通常在数据部分中分配,所以不应该释放它们。
发布于 2011-07-08 15:30:28
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. */
}因此,线程函数必须分配一些内容。
https://stackoverflow.com/questions/6626685
复制相似问题