2016-08-18 128 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 
} 

我怎麼保證,當線程執行完成的線程刪除,並且沒有內存泄漏而不等待線程在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

如果你想確保你退出main在那之前你返回正確的前線程完成幫助main使用

thread_pulse.join(); 

這將等待thread_pulse繼續之前完成。

如果你如果線程完成,然後不在乎你可以在創建後detach它像

thread_pulse.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