jeudi 2 mai 2019

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.

Aucun commentaire:

Enregistrer un commentaire