gpt4 book ai didi

c - pthread_exit 与返回

转载 作者:IT老高 更新时间:2023-10-28 12:38:23 25 4
gpt4 key购买 nike

我有一个可连接的 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);

我的实际问题是三管齐下的:

  1. 有人可以解释为什么 return 语句没有泄漏吗?
  2. 在退出线程方面,这两个语句之间是否存在一些根本区别?
  3. 如果是这样,什么时候应该优先考虑其中一个?

最佳答案

以下最小测试用例展示了您描述的行为:

#include <pthread.h>
#include <unistd.h>

void *app1(void *x)
{
sleep(1);
pthread_exit(0);
}

int main()
{
pthread_t t1;

pthread_create(&t1, NULL, app1, NULL);
pthread_join(t1, NULL);

return 0;
}

valgrind --leak-check=full --show-reachable=yes 显示由 pthread_exit() 调用的函数分配的 5 个 block ,这些 block 未被释放但仍可在进程退出。如果将pthread_exit(0);替换为return 0;,则5个 block 不分配。

但是,如果您测试创建和加入大量线程,您会发现退出时使用的未释放内存量没有增加。这以及它仍然可以访问的事实表明您只是看到了 glibc 实现的奇怪之处。几个 glibc 函数在第一次调用时使用 malloc() 分配内存,它们在进程生命周期的剩余时间内一直分配内存。 glibc 不会费心在进程退出时释放此内存,因为它知道该进程无论如何都会被拆除 - 这只是浪费 CPU 周期。

关于c - pthread_exit 与返回,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3844678/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com