What is different between join() and detach() for multi threading in C++?

后端 未结 2 1653
日久生厌
日久生厌 2020-12-07 15:06

What is different between join() and detach() in multi threading in C++? Does join() kill the thread?

2条回答
  •  情话喂你
    2020-12-07 15:25

    join() doesn't kill the thread. Actually it waits until thread main function returns. So if your thread main function looks like this:

    while (true) {
    }
    

    join() is going to wait forever.

    detatch() doesn't kill thread either. Actually it tells std::thread that this thread should continue to run even when std::thread object is destroyed. C++ checks in std::thread destructor that thread is either joined or detached and terminates program if this check fails.

    So if you uncomment first line in main function of the following code it will crash. If you uncomment second or third line it will work ok.

    #include 
    
    void func() {
    }
    
    void fail1() {
        std::thread t(func);
        // will fail when we try to destroy t since it is not joined or detached
    }
    
    void works1() {
        std::thread t(func);
        t.join();
    }
    
    void works2() {
        std::thread t(func);
        t.detach();
    }
    
    int main() {
        // fail1();
        // works1();
        // works2();
    }
    

提交回复
热议问题