是否可以创建boost :: thread并在后台运行(作为守护程序)?
我正在尝试以下操作,但是主退出时线程死了。
/*
* 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线程] $
最佳答案
当您的main()
退出时,该进程的所有其他线程都将终止(假设Linux,对于Windows无法说)。
为什么不只是在join()
末尾的main()
后台线程?甚至更好-将主线程用作“守护程序”线程?
关于c++ - 将加速线程作为守护程序运行,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/11137959/