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]$