Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does thread::detach() work in C++11?

I wrote the following code and am unable to understand why doesn't it prints out all the no's(i.e. 0 to -99) in threadFunc() as it does with main() thread.

#include<iostream>
#include<thread>
#include<string>
#include<mutex>
#include<chrono>

using namespace std;

mutex mu;

void threadFunc(){
    for(int i=0;i>-100;i--){
    std::this_thread::sleep_for(std::chrono::milliseconds(30)); /*delay for 30ms*/
    mu.lock();
    cout<<"Thread:  "<<i<<endl;
    mu.unlock();
    }
}

main(){

    thread t1(threadFunc);   


    for(int i=0;i<100;i++){
    mu.lock();
    cout<<"Main:  "<<i<<endl;
    mu.unlock();    
    }


    cout<<"End of Main"<<endl;  

    t1.detach();   
}

The output of the program is:

Main: 0  
Main: 1  
.  
.  
.  
Main: 99  
End of Main.  
Thread: -1 
like image 766
No Sound Avatar asked Apr 15 '16 17:04

No Sound


1 Answers

Process terminates when main() exits, and all threads are killed. You observe this behavior in your program.

Detach basically says that from now on, you can't join this thread. But if you can't join it, you can't make your main() to wait until it completes (unless you use other synchronization primitives) - and thus it is happily exiting.

This is why I strongly discourage everybody from using detached threads, they are very hard to do properly.

like image 120
SergeyA Avatar answered Sep 21 '22 18:09

SergeyA