Search code examples
multithreadingc++11detach

detach call is not working as per expectation


Need help why below codes are working differently. In this code thread is not printing anything after main exit:

#include <iostream>
#include <chrono>
#include <thread>

using namespace std;

void Run()
{

        cout<<"=== "<< "start_point" <<" ==="<<endl;
        std::this_thread::sleep_for(std::chrono::seconds(1));

        cout<<"=== "<< "start_point" <<" ==="<<endl;
        std::this_thread::sleep_for(std::chrono::seconds(1));

        cout<<"=== "<< "start_point" <<" ==="<<endl;
        std::this_thread::sleep_for(std::chrono::seconds(1));

        cout<<"=== "<< "start_point" <<" ==="<<endl;
        std::this_thread::sleep_for(std::chrono::seconds(1));

        cout<<"=== "<< "start_point" <<" ==="<<endl;
        std::this_thread::sleep_for(std::chrono::seconds(1));

        cout<<"=== "<< "start_point" <<" ==="<<endl;
        std::this_thread::sleep_for(std::chrono::seconds(1));

        cout<<"=== "<< "start_point" <<" ==="<<endl;

}

int main()
{
    std::thread th(Run);

    th.detach();

    std::this_thread::sleep_for(std::chrono::seconds(2));

    cout<<"==== Ending main ==="<<std::endl;
}

But Here proper messages getting printed after thread exit:

void independentThread() 
{
    std::cout << "Starting concurrent thread.\n";
    std::this_thread::sleep_for(std::chrono::seconds(2));
    std::cout << "Exiting concurrent thread.\n";
}

void threadCaller() 
{
    std::cout << "Starting thread caller.\n";
    std::thread t(independentThread);
    t.detach();
    std::this_thread::sleep_for(std::chrono::seconds(1));
    std::cout << "Exiting thread caller.\n";
}

int main() 
{
    threadCaller();
    std::this_thread::sleep_for(std::chrono::seconds(1));
}

Should be something very small and I am missing it. Compiler information: g++ / Mac / c++11

tried to search on google but not luck.

Edit-1: Result for first program:

=== start_point ===
=== start_point ===
==== Ending main ===

Result for 2nd Program:

Starting thread caller.
Starting concurrent thread.
Exiting thread caller.
Exiting concurrent thread.

Solution

  • That code looks like it is executing correctly to me.

    Normally when thread's destructor runs, it will wait for the thread to finish before exiting. However, when you call detach(), you are circumventing this behavior - the current method won't wait for the thread to finish.

    Since the thread will run for (approximately) 6 seconds, the sleep in main() doesn't wait long enough for the threat to finish, so it will exit before the thread has finished. Depending on the environment, it's possible that exiting main() will also exit the program - meaning the thread doesn't ever get a chance to print all of its messages before the program exits.

    If you want to explicitly wait for the thread to finish before continuing execution, you should call thread::join().