pthread_detach问题
直到最近,我的印象是,如果您在生成线程后“分离”它,那么即使“主”线程终止后,该线程仍然存在。
但一个小实验(如下所列)与我的信念相反。我希望分离的线程即使在 main 终止后也能继续打印“从分离的线程说话”,但这似乎没有发生。应用程序显然终止了...
“主”问题返回0之后“分离”线程是否会死亡?
#include <pthread.h>
#include <stdio.h>
void *func(void *data)
{
while (1)
{
printf("Speaking from the detached thread...\n");
sleep(5);
}
pthread_exit(NULL);
}
int main()
{
pthread_t handle;
if (!pthread_create(&handle, NULL, func, NULL))
{
printf("Thread create successfully !!!\n");
if ( ! pthread_detach(handle) )
printf("Thread detached successfully !!!\n");
}
sleep(5);
printf("Main thread dying...\n");
return 0;
}
Till recently, I was under the impression that if you "detach" a thread after spawning it, the thread lives even after the "main" thread terminates.
But a little experiment (listed below) goes contrary to my belief. I expected the detached thread to keep printing "Speaking from the detached thread" even after main terminated, but this does not seem to be happening. The application apparently terminates...
Do the "detached" threads die after "main" issues return 0?
#include <pthread.h>
#include <stdio.h>
void *func(void *data)
{
while (1)
{
printf("Speaking from the detached thread...\n");
sleep(5);
}
pthread_exit(NULL);
}
int main()
{
pthread_t handle;
if (!pthread_create(&handle, NULL, func, NULL))
{
printf("Thread create successfully !!!\n");
if ( ! pthread_detach(handle) )
printf("Thread detached successfully !!!\n");
}
sleep(5);
printf("Main thread dying...\n");
return 0;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
pthread_detach
只是意味着您永远不会再次加入线程。这使得 pthread 库知道一旦线程退出(分离的情况),它是否可以立即处理线程资源,或者是否必须保留它们,因为您稍后可能会在线程上调用pthread_join
。一旦 main 返回(或退出),操作系统将捕获所有线程并销毁您的进程。
pthread_detach
just means that you are never going to join with the thread again. This allows the pthread library to know whether it can immediately dispose of the thread resources once the thread exits (the detached case) or whether it must keep them around because you may later callpthread_join
on the thread.Once main returns (or exits) the OS will reap all your threads and destroy your process.
pthread_detach
并不做你想象的那样 - 它向实现表明具有指定 ID 的线程正在使用的空间一旦终止就可以回收,即。不会对其执行任何pthread_join
操作。一旦包含线程的进程终止,所有线程也将终止。
pthread_detach
does not do what you think it does - it indicates to the implementation that the space the thread with the specified ID is using can be reclaimed as soon as it terminates, ie. nopthread_join
operation will be performed on it.All threads are terminated once the process containing them is terminated.
是的,分离的线程将在
return 0
后死亡。来自
man pthread_detach
的NOTES部分Yes, the detached threads will die after
return 0
.From the NOTES section of
man pthread_detach
来自man pthread_detach:
From
man pthread_detach
:引用Linux 程序员手册:
另来自 Linux 程序员手册:
To quote the Linux Programmer's Manual:
Also from the Linux Programmer's Manual: