detach,主线程终止后子线程会结束吗

    此前,我对detach的理解是,当主线程退出后,子线程能够继续存在。实际上,当主线程退出后,子线程也随之结束了。先看一个例子:

#include <iostream>
#include <thread>
#include <unistd.h>

using 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。真的吗?真的,请看下图:

能否让主进程退出之后,不把子进程给结束掉呢?请看下例:

#include <iostream>
#include <thread>
#include <unistd.h>

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.”

如果子线程退出了,主进程也会随之而去。真的吗?请看下例:

#include <iostream>
#include <thread>
#include <unistd.h>

int main()
{
	std::thread my_thread([]{
		cout << "thread bye" << endl;
		exit(0);//线程主动退出,此时,主进程会随之结束
        //return 0; //线程正常结束,主进程不受影响
	});
	this_thread::sleep_for(chrono::seconds(2));
	my_thread.detach(); 
	cout << "main bye" << endl; 
}

运行结果验证了上述结论。所以,一直以来,我对detach一直有误区。detach,主要的还是把主进程和子线程分离了,使二者能够独立的运行。但是,他们依然同生共死,不离不弃。

总结出以下结论:

1.主进程结束时(调用return/exit),子线程会随之结束。可以通过pread_exit退出进程而不杀掉其子线程。

2.用detach分离子线程和主进程,二者任意一个退出,整个进程(包括线程)都会结束。如果线程是正常结束(代码执行完毕或者调用了return),主进程不受影响。

3.在main函数中,如果不显示的调用return,编译器会自动给加一句return 0。

  • 10
    点赞
  • 27
    收藏
    觉得还不错? 一键收藏
  • 5
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值