2

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.

Community
  • 1
  • 1
neo
  • 969
  • 1
  • 11
  • 23

1 Answers1

0

The standard defines the scope of thread as being the program:

1.10/1: A thread of execution (also known as a thread) is a single flow of control within a program (...) The execution of the entire program consists of an execution of all of its threads.

The standard says about detached threads:

30.3.3/1: A thread of execution is detached when no thread object represents that thread.

So there's nothing in the standard that suggests hat a thread could survive its program.

If you want to keep something running in background after the end of the program, you have to fork or create a separate process that will run in the background with its own resources and threads.

Christophe
  • 68,716
  • 7
  • 72
  • 138