【发布时间】:2011-04-20 04:04:26
【问题描述】:
我有一个可连接的 pthread runner 函数,定义如下:
void *sumOfProducts(void *param)
{
...
pthread_exit(0);
}
这个线程应该加入主线程。
每当我通过 Valgrind 运行我的程序时,我都会得到以下漏洞:
LEAK SUMMARY:
definitely lost: 0 bytes in 0 blocks
indirectly lost: 0 bytes in 0 blocks
possibly lost: 0 bytes in 0 blocks
still reachable: 968 bytes in 5 blocks
suppressed: 0 bytes in 0 blocks
ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 15 from 10)
我查看了 pthreads 的手册页,上面写着:
The new thread terminates in one of the following ways:
* It calls pthread_exit(3), specifying an exit status value that is
available to another thread in the same process that calls
pthread_join(3).
* It returns from start_routine(). This is equivalent to calling
pthread_exit(3) with the value supplied in the return statement.
* It is canceled (see pthread_cancel(3)).
* Any of the threads in the process calls exit(3), or the main thread
performs a return from main(). This causes the termination of all
threads in the process.
奇迹般地,当我用 return 语句替换 pthread_exit() 时,泄漏消失了。
return(NULL);
我的实际问题是三管齐下的:
- 谁能解释为什么 return 语句没有泄漏?
- 在退出线程方面,这两个语句之间是否存在一些根本区别?
- 如果是这样,什么时候应该优先选择一个?
【问题讨论】:
-
你真的在使用 C++ 吗? C++ 使用作用域来销毁对象并返回将“离开”该作用域,而 pthread_exit 不会。
-
很抱歉,我的问题中从未提及 C++。到目前为止,我正在用 C 语言做所有事情。