中国水利建设网站,网站备案取名,中国企业500强公司排名,自建电商平台方案此前#xff0c;我对detach的理解是#xff0c;当主线程退出后#xff0c;子线程能够继续存在。实际上#xff0c;当主线程退出后#xff0c;子线程也随之结束了。先看一个例子#xff1a;
#include iostream
#include thread
#include unistd.h我对detach的理解是当主线程退出后子线程能够继续存在。实际上当主线程退出后子线程也随之结束了。先看一个例子
#include iostream
#include thread
#include unistd.husing namespace std;int main()
{std::thread my_thread([]{while(1) {this_thread::sleep_for(chrono::seconds(1));cout in thread endl;}});this_thread::sleep_for(chrono::seconds(2));my_thread.detach(); cout after detach endl;
} 运行结果为
in thread after detach
问题一主进程结束之后子线程会跟着结束吗 这是关于detach的定义
https://legacy.cplusplus.com/reference/thread/thread/detach/
Detaches the thread represented by the object from the calling thread, allowing them to execute independently from each other.
既然都allowing them to execute independently from each other了为什么主进程退出的时候子线程也跟着走了在linux系统中当主进程结束的时候子进程确实会跟着结束的。那么问题来了main执行完之后主进程就结束了吗是的的确如此上面的例子已经说明了这个结论。那么main是如何结束的因为调用了return。可是我在代码中没有没有调用return因为编译器自动给加了一句return 0。真的吗真的请看下图 能否让主进程退出之后不把子进程给结束掉呢请看下例
int main()
{std::thread my_thread([]{while(1) {this_thread::sleep_for(chrono::seconds(1));cout in thread endl;}});this_thread::sleep_for(chrono::seconds(2));my_thread.detach(); cout after detach endl; pthread_exit(nullptr);
}
主进程退出后子线程依然活蹦乱跳的。这一次由于主进程通过pthread_exit猝然长逝来不及挥一挥衣袖也来不及带走一个线程。
问题二 detach之后如果子线程退出了会发生什么
“Both threads continue without blocking nor synchronizing in any way. Note that when either one ends execution, its resources are released.”
如果子线程退出了主进程也会随之而去。真的吗请看下例
int main()
{std::thread my_thread([]{cout thread bye endl;exit(0);});this_thread::sleep_for(chrono::seconds(2));my_thread.detach(); cout main bye endl;
}
运行结果验证了上述结论。所以一直以来我对detach一直有误区。detach主要的还是把主进程和子线程分离了使二者能够独立的运行。但是他们依然同生共死不离不弃。
总结出以下结论
1.主进程结束时调用return/exit子线程会随之结束。可以通过pread_exit退出进程而不杀掉其子线程。
2.用detach分离子线程和主进程二者任意一个结束整个进程包括线程都会结束。
3.在main函数中如果不显示的调用return编译器会自动给加一句return 0。