I was going through this post on stack overflow in which the accepted answer says:
what happens to a detached thread when main() exits is:
It continues running (because the standard doesn't say it is stopped), and that's well-defined, as long as it touches neither (automatic|thread_local) variables of other threads nor static objects.
While in this post the accepted answer says that:
Process terminates when main() exits, and all threads are killed.
To see the behavior, I tested below code on g++ (Ubuntu 4.8.4-2ubuntu1~14.04.3) 4.8.4 which suggests that once the main thread exit other detach thread also exit.
#include <iostream>
#include <thread>
#include <unistd.h>
#include <fstream>
using namespace std;
void foo()
{
std::cout<<"Inside foo\n";
int i=0;
ofstream myfile;
while(i<10)
{
std::cout<<"Inside while\n";
myfile.open ("/home/abc/example.txt",ios::app);
myfile << "Writing this to a file.\n";
myfile.close();
i++;
sleep(1);
}}
int main()
{
std::thread first (foo);
first.detach();
sleep(5);
return 0;
}
So why in many posts here on stack overflow suggests that detach thread continues running in background even if main thread exit? In what condition the detach thread continues to run in background when main exit and which one of the above statement is true?
Thanks in advance.
Aucun commentaire:
Enregistrer un commentaire