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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With