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

发布时间 2023-04-26 17:43:36作者: 牛博张

transfrom: https://blog.csdn.net/a0408152/article/details/129093394

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

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

using namespace std; int main() { std::thread my_thread([]{ while(true) { this_thread::sleep_for(chrono::seconds(1)); cout << "int child thread." << endl; } cout << "end child thread while" << endl; }); this_thread::sleep_for(chrono::seconds(2)); my_thread.detach(); this_thread::sleep_for(chrono::seconds(3)); cout << "after detach" << endl; }

 run result:

int child thread.
int child thread.
int child thread.
int child 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。