0

Is it possible to create a boost::thread and run it in the background (as a daemon)? I am trying to the following but my thread dies when main exits.

/*
 * Create a simple function which writes to the console as a background thread.
 */
void countDown(int counter) {
    do {
        cout << "[" << counter << "]" << endl;
        boost::this_thread::sleep(seconds(1));
    }while(counter-- > 0);
}

int main() {
    boost::thread t(&countDown, 10);

    if(t.joinable()) {
        cout << "Detaching thread" << endl;
        t.detach(); //detach it so it runs even after main exits.
    }

    cout << "Main thread sleeping for a while" << endl;
    boost::this_thread::sleep(seconds(2));
    cout << "Exiting main" << endl;
    return 0;
}

[rajat@localhost threads]$ ./a.out

Detaching thread

Main thread sleeping for a while

[10]

[9]

Exiting main

[rajat@localhost threads]$

Rajat
  • 467
  • 1
  • 5
  • 15

1 Answers1

2

When your main() exits all other threads of the process are terminated (assuming Linux, can't say for Windows).

Why not just join() that background thread at the end of the main()? Or even better - use the main thread as the "daemon" thread?

Nikolai Fetissov
  • 82,306
  • 11
  • 110
  • 171
  • Thanks, but what's the purpose of the thread.detach() then? I thought it was there to allow threads to run even after main thread exits. Is there a way that I can run say 10 threads in the background without joining them..? If I join them, then I'll need to run my application in the background using nohup. – Rajat Jun 21 '12 at 12:30
  • Detaching a thread is to indicate that the resources for the thread can be released and as mentioned [here](http://www.boost.org/doc/libs/1_42_0/doc/html/thread/thread_management.html#thread.thread_management.thread.detach), thread ceases to exist after detachment. – panickal Jun 21 '12 at 12:38
  • @Rajat, read up on how Linux processes and threads work, you have some skewed assumptions here. – Nikolai Fetissov Jun 21 '12 at 12:55