gpt4 book ai didi

c++ - 是否需要分离 pthread 以防止内存泄漏?

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:29:51 25 4
gpt4 key购买 nike

在我的程序中,我处理新线程

 pthread_t thread;
pthread_create(&thread, NULL,
c->someFunction, (void *) fd); //where fd is ID of the thread

问题很简单 - 如果我只是让 someFunction 完成,是否需要在 C++ 中调用一些东西,例如join 或其他任何东西,以防止 内存泄漏 或内存是否自动释放??

最佳答案

来自opengroup page for pthread_join ,

The pthread_join() function provides a simple mechanism allowing an application to wait for a thread to terminate. After the thread terminates, the application may then choose to clean up resources that were used by the thread. For instance, after pthread_join() returns, any application-provided stack storage could be reclaimed.

The pthread_join() or pthread_detach() function should eventually be called for every thread that is created with the detachstate attribute set to PTHREAD_CREATE_JOINABLE so that storage associated with the thread may be reclaimed.

来自man page of pthread_join

Failure to join with a thread that is joinable (i.e., one that is not detached), pro‐ duces a "zombie thread". Avoid doing this, since each zombie thread consumes some system resources, and when enough zombie threads have accumulated, it will no longer be possible to create new threads (or processes).

There is no pthreads analog of waitpid(-1, &status, 0), that is, "join with any ter‐ minated thread".

If you believe you need this functionality, you probably need to rethink your application design.

如果你这样做 pthread_detach ,

The pthread_detach() function shall indicate to the implementation that storage for the thread thread can be reclaimed when that thread terminates

如果你不分离加入一个joinable线程,它会造成资源浪费

关于c++ - 是否需要分离 pthread 以防止内存泄漏?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16936179/

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