2012-06-21 75 views
0

是否可以創建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; 
} 

[拉杰特@本地線程] $ ./a.out

拆卸螺紋

主線程睡眠一會兒

[10]

[9]

正在退出主

[rajat @​​ localhost threads] $

回答

2

當你的main()退出進程的所有其他線程都被終止(假設Linux不能用於Windows)。

爲什麼不只是join()後臺線程在main()的末尾?或者甚至更好 - 使用主線程作爲「守護進程」線程?

+0

謝謝,但thread.detach()的目的是什麼呢?我認爲在主線程退出後允許線程運行。有沒有一種方法,我可以在沒有加入他們的情況下在後臺運行10個線程..?如果我加入他們,那麼我需要使用nohup在後臺運行我的應用程序。 – Rajat

+0

分離一個線程是爲了表明線程的資源可以被釋放,並且如[在這裏]提到的(http://www.boost.org/doc/libs/1_42_0/doc/html/thread/thread_management.html#thread .thread_management.thread.detach),線程在分離後不再存在。 – panickal

+0

@Rajat,閱讀Linux進程和線程是如何工作的,你在這裏有一些歪曲的假設。 –