I am writing the following c++ code to create a detach thread :
void threadF() {
ofstream f("data") ;
for(int i=1; i<=5; i++) {
f<<"t1:::"<<i<<"\n" ;
f.flush() ;
sleep(1) ;
}
f.close() ;
}
int main() {
thread t1(threadF) ;
cout<<"main #1\n" ;
sleep(2) ;
t1.detach() ;
cout<<"main #2\n" ;
}
When I run this code, I have the following observations :
- main exits after 2 secs (as expected)
- the detach child thread also seems to be running only for 2secs because the output
data
file contains only 2 lines.
I expected that the thread should have executed completely and that the output data
file should have contained 5 lines. This is not happening
I need an explanation for this behavior.
AS per the ink What happens to a detached thread when main() exits?, does it mean that the detached thread would automatically terminate when the main exits ?