[英]Multithreaded C++ Program Not Running In Parallel Using vector<thread> and .join()
[英]Multithreaded program thread join issues
我目前正在編寫一個多線程程序,根據某些情況,有時可能會創建一個線程。 如果創建了這個線程,它需要獨立於所有其他線程運行,我不能阻止任何其他線程等待它加入。 生成的線程運行的時間長度各不相同; 有時它可能需要幾個小時。
我已經嘗試生成線程並在類的析構函數中添加一個正常工作的連接,但是如果生成的線程中的代碼在析構函數被調用之前很長時間(這將是99%的時間)我會像殺死自己的線程釋放所有資源等。
我考慮使用detach,但你不能重新加入一個分離的線程,並且在這個線程完成之前調用析構函數然后生成的線程將無法完成並且可能產生災難性的后果。
是否有任何可能的解決方案可以確保線程在類被破壞之前完成,並且一旦線程完成其工作就允許它加入?
我正在使用boost / c ++ 11進行線程化。 任何幫助都將非常感激。
謝謝
線程可以自行分離,釋放其資源。 如果析構函數看到線程可以連接,即仍然在運行,那么讓它加入。 如果線程到達終點,則自行分離。 可能的競爭條件:is_joinable()在析構函數中返回true - 線程分離自身 - 析構函數連接並失敗。 所以使用一個互斥鎖來保護線程的死亡:
struct ThreadContainer
{
std::mutex threadEndMutex;
std::thread theThread;
ThreadContainer()
: theThread([=]()
{
/* do stuff */
// if the mutex is locked, the destructor is just
// about to join, so we let him.
if (threadEndMutex.try_lock())
theThread.detach();
})
{}
~ThreadContainer()
{
// if the mutex is locked, the thread is just about
// to detach itself, so no need to join.
// if we got the mutex but the thread is not joinable,
// it has detached itself already.
if (threadEndMutex.try_lock() && theThread.is_joinable())
theThread.join();
}
};
PS:你可能甚至不需要調用is_joinable,因為如果線程自己分離,它永遠不會解鎖互斥鎖並且try_lock失敗。
PPS:您可以使用std :: atomic_flag代替互斥鎖:
struct ThreadContainer
{
std::atmoic_flag threadEnded;
std::thread theThread;
ThreadContainer()
: threadEnded(ATOMIC_FLAG_INIT)
, theThread([=]()
{
/* do stuff */
if (!threadEnded.test_and_set())
theThread.detach();
})
{}
~ThreadContainer()
{
if (!threadEnded.test_and_set())
theThread.join();
}
};
您可以在“獨立”線程算法中定義暫停/步驟,並在每個步驟中查看一個全局變量,該變量可幫助您決定取消計算並自動銷毀,或繼續計算您的線程。
如果全局變量不夠,即如果需要更精確的粒度,則應為線程函數定義一個仿函數對象,該仿函數具有方法kill()。 在將它們作為線程啟動后,您將保留對仿函數的引用。 當你調用MyThreadFunctor :: kill()時,它會設置一個布爾字段,並在functor線程函數本身的計算的每個步驟中檢查此字段。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.