我有一個有boost::thread成員變數的類。我有一個在該執行緒中運行的私有成員函式(參見下面的代碼)。
class Human
{
public:
Human()
: m_thinkThread(&Human::think, this)
{ }
~Human()
{
m_thinkThread.interrupt();
m_thinkThread.join();
}
private:
void think()
{
// do some thinking...
}
boost::thread m_thinkThread;
};
- 我需要
interruptandjoin呼叫,因此需要自定義解構式嗎?還是默認解構式會負責干凈地退出?如果我只需要默認的解構式,那么它“在幕后”做了什么來確保執行緒干凈地退出? - 但是,如果我確實需要
interruptandjoin呼叫,那么我當前的設定有一個錯誤,因為join()canthrow,這將是解構式中未捕獲的例外。我將如何處理這種情況?
謝謝
uj5u.com熱心網友回復:
我需要中斷和加入呼叫,因此需要自定義解構式嗎?還是默認解構式會負責干凈地退出?如果我只需要默認的解構式,那么它“在幕后”做了什么來確保執行緒干凈地退出?
是的。有std::jthread更新的標準版本,可以自動加入。
但是,如果我確實需要中斷和加入呼叫,那么我當前的設定有一個錯誤,因為 join() 可以拋出,這將是解構式中未捕獲的例外。我將如何處理這種情況?
如果我沒記錯的話,還有一個join_nothrow手術。如果我記得一個實作細節,請考慮使用執行緒保護。
這似乎是在 Anthony Williams 的“Concurrency In Action”(第 2.1.3 章)之后添加到 Boost Thread 中的,但似乎從未收到過檔案。
struct Human
{
Human() : m_thinkThread(&Human::think, this) {}
private:
void think() const;
boost::thread m_thinkThread;
boost::thread_guard<boost::interrupt_and_join_if_joinable> m_guard{m_thinkThread};
};
住在科利魯
void Human::think() const {
while (true) {
boost::this_thread::sleep_for(boost::chrono::milliseconds(1500));
std::cout << "Thinking..." << std::endl;
}
}
int main() {
Human plight;
boost::this_thread::sleep_for(boost::chrono::seconds(10));
}
印刷
Thinking...
Thinking...
Thinking...
Thinking...
Thinking...
Thinking...
然后在 10 秒后干凈地關閉。
注意事項
已經有一些版本的 boost 在嵌套可中斷執行緒的情況下使用執行緒保護會出現未處理的例外:請參閱https://github.com/boostorg/thread/issues/366
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/464677.html
上一篇:重構:在子函式中委托友誼
