[英]Terminating running thread c++ std::thread
我想運行一個執行以下操作的線程:
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
}
如果要確保線程在退出main
之前完成,那么就在退出main
使用之前
thread_pulse.join();
在繼續之前,這將等待thread_pulse
完成。
如果您如果線程完成,然后不關心你可以detach
它像
thread_pulse.detach();
創建它之后。 這將使程序結束而不會引發異常。
另外,您可以構建一個包裝器類來存儲線程,當線程被銷毀時,它將為您調用join
或detach
,因此您不必記住。 您可以使用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()
或者只是硬編碼行為。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.