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;
}

[rajat@localhost スレッド]$ ./a.out

糸の取り外し

メインスレッドがしばらく休眠中

[10]

[9]

メインを終了

[rajat@localhost スレッド]$

4

1 に答える 1

2

終了するmain()と、プロセスの他のすべてのスレッドが終了します (Linux の場合、Windows の場合は言えません)。

join()の最後にあるバックグラウンド スレッドだけではないのはなぜmain()ですか。またはさらに良い-メインスレッドを「デーモン」スレッドとして使用しますか?

于 2012-06-21T12:24:49.633 に答える