是否可以创建 boost::thread 并在后台运行它(作为守护进程)?我正在尝试以下操作,但是当 main 退出时我的线程死了。
/*
* 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 线程]$ ./a.out
拆线
主线程休眠一段时间
[10]
[9]
退出主
[rajat@localhost 线程]$