![](/img/trans.png)
[英]Why is destructor of boost::thread detaching joinable thread instead of calling terminate() as standard suggests?
[英]Terminate current thread in destructor
在一個項目中,我們正在包裝器類中創建多個狀態機。 每個包裝器都在其自己的線程中運行。 作業完成后,將調用包裝器類析構函數,並在其中停止線程。
雖然如果我們使用thread.join()
, thread.join()
遇到死鎖(因為它試圖連接自己)。 我們可以以某種方式向另一個線程發出信號,但這似乎有些混亂。
有什么方法可以在對象破壞時正確終止正在運行類的線程?
thread.join()
不會停止線程。 它等待線程完成,然后返回。 為了停止線程,您必須有某種方法告訴線程停止,並且線程必須檢查是否應該停止。 一種方法是使用原子布爾:
class my_thread {
public:
my_thread() : done(false) { }
~my_thread() { done = true; thr.join(); }
void run() { thread th(&my_thread::do_it, this); swap(th, thr); }
private:
void do_it() { while (!done) { /* ... */ } }
std::thread thr;
std::atomic<bool> done;
};
那是我的頭頂。 未經編譯,未經測試。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.