我举了一个例子
https://www.kernel.org/doc/man-pages/online/pages/man3/pthread_create.3.html
通过使用 pthread_create
创建线程而无需调用 pthread_join
,使其无限运行( sleep 时间小,因此 CPU 使用率不是瓶颈,因此无需线程排队)。这会导致内存泄漏,最终 PC 内存不足。当我在创建线程后立即添加 pthread_detach
时,线程程序表现良好,一段时间后内存使用量保持不变。
我的印象是,当一个线程退出时(在关闭函数的 }
时,如果将其提供给 pthread_create
)它的所有资源都会被清除。
最佳答案
I was under impression that when a thread exits ( at closing } of the function that if given to pthread_create) all its resources are cleaned.
这是一个错误的印象。正如您所说,当您调用 pthread_join 或线程是分离线程时,所有资源都会为已完成的线程释放。
对于非分离线程,必须保留一些资源 - 否则您无法通过稍后调用 pthread_join 获得线程的返回值。无法加入分离的线程,因此无法从中获取退出值。
许多实现将此返回值存储在线程的堆栈中,因此保留整个堆栈,直到有人在非分离线程上调用 pthread_join。
关于c - 为什么在 pthread_create 后未分离线程时未加入的 pthread 会泄漏资源,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13865375/