0
부스트 :: 스레드를 생성하여 백그라운드에서 실행할 수 있습니까 (데몬)? 다음을 시도하지만 주 스레드가 종료 될 때 스레드가 종료됩니다.부울 스레드를 데몬으로 실행
/*
* 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;
}
[라자 @ localhost를 스레드] 잠시
[10]
[9]
에 대한 스레드를메인 스레드 수면을 분리 $ ./a.out
메인 종료
[rajat @ localhost threads] $
감사합니다.하지만 thread.detach()의 목적은 무엇입니까? 주 스레드가 종료 된 후에도 스레드가 실행될 수 있다고 생각했습니다. 거기에 합류하지 않고 백그라운드에서 10 개의 스레드를 실행할 수있는 방법이 있습니까? 만약 그들과 합치면 nohup을 사용하여 백그라운드에서 응용 프로그램을 실행해야 할 것입니다. – Rajat
스레드 분리는 해당 스레드의 자원을 해제 할 수 있음을 나타냅니다. [여기] (http://www.boost.org/doc/libs/1_42_0/doc/html/thread/thread_management.html#thread) .thread_management.thread.detach), 분리 후 스레드가 존재하지 않습니다. – panickal
@Rajat, 리눅스 프로세스와 쓰레드가 어떻게 동작하는지에 대해 읽어 보았을 때, 당신은 약간의 가정이 왜곡되어있다. –