2016-08-18 12 views
0
私はこのような単純なものないスレッド実行したい

終端実行中のスレッドのC++のstd ::スレッド

main(){ 
    std::thread thread_pulse([=]{ 
     *this->do_adress = true; 
     std::this_thread::sleep_for(std::chrono::milliseconds(milliseconds)); 
     *this->do_adress = false; 
     //delete this thread to avoid memory leaks 
    }); 
    //do some other stuff without waiting for the thread to terminate 
} 

をどのように私は、スレッドの実行が行われたときに、スレッドが削除されたことを保証しないと何もありませんスレッドがメインで実行を終了するのを待たずにメモリリークが発生する?

EDIT:助けを

おかげで、あなたはあなたがから戻る前に、あなたは右クリックmainを終了する前に必ずスレッドが実行されるようにしたい場合は、私は

main(){ 
    std::thread ([=]{ 
     *this->do_adress = true; 
     std::this_thread::sleep_for(std::chrono::milliseconds(milliseconds)); 
     *this->do_adress = false; 
     //delete this thread to avoid memory leaks 
    }).detach; 
    //do some other stuff without waiting for the thread to terminate 
} 
+0

'std :: thread thread_pulse(...); thread_pulse.detach(); ' –

答えて

4

を望んでいたとして、これは働いていたヘルプwhith main

thread_pulse.join(); 

使用これは、上の続行する前に終了するthread_pulseを待ちます。

あなたはそれを作成した後、あなたは

thread_pulse.detach(); 

ようdetachスレッドが終了したならば、あなたができることを気にしない場合。これにより例外がスローされることなくプログラムが終了します。


別の方法としては、スレッドを保存するラッパークラスを構築することができ、それが破壊されますときに覚えておく必要はありませんので、それはあなたのためにjoindetachを呼び出します。あなたはScott Myers ThreadRAII

class ThreadRAII 
{  
public:  
    ThreadRAII(std::thread&& thread): t(std::move(thread)) {} 
    ~ThreadRAII() { if (t.joinable()) t.join(); } 
private:  
    std::thread t;  
}; 

のようなものを使用し、どちらかあなたはjoin()するかどうかdetach()や行動だけでハードコード選択できるように変更することができます。

+0

私は実際にデタッチを望んでいました。ありがとう、私は将来の参照のために質問を編集します – heczaco

+0

@heczaco問題ありません。喜んで助けてください。 – NathanOliver

関連する問題