[英]std::thread created thread not handling exceptions
我正在創建一些將分離的std :: threads。 我想讓它們運行很長時間,並希望它們自己處理異常。
我使用std :: thread(Function)創建了一個線程,並在釋放互斥鎖之前調用了detach,其中Function執行以下操作:
void BlockStart() noexcept {
std::lock_guard<std::mutex> sync(lock);
}
void Function()
{
BlockStart();
try
{
throw;
}
catch(...)
{
std::cerr << "Caught something...\n";
}
}
每次我運行此代碼時,都不會調用異常處理程序。 調用std :: terminate()的默認處理程序,該處理程序調用abort。
我如何獲得std :: thread啟動線程來處理異常?
基於此問題的答案: https : //stackoverflow.com/a/5378736/1619294
如果你
throw;
單獨運行,並且當前沒有異常可以重新拋出,然后程序突然結束。 (更具體地說,調用terminate()
。)
您可能想要做類似的事情
void Function()
{
try
{
SomeOtherFunction();
}
catch(...)
{
std::cerr << "Caught something...\n";
}
}
另外,請注意, BlockStart()
函數中的鎖定防護+互斥鎖只會在函數的持續時間內阻塞,並且在返回后將不會持續存在。 解決方案是在Function()
內設置鎖衛鎖
void Function() {
std::lock_guard<std::mutex> sync(lock);
...
單獨調用throw
會重新引發當前異常,但這僅在catch
塊內部調用時有效。 如果您在沒有當前異常的情況下try
在try
塊內自行調用throw
,則會調用terminate()
並導致應用程序死亡。 你必須告訴throw
什么的里面時拋出try
塊,如:
void Function()
{
BlockStart();
try
{
throw std::runtime_error("something bad happened");
}
catch(const std::exception& e)
{
std::cerr << "Caught something... " << e.what() << std::endl;
}
}
同樣,在BlockStart()
內使用std::lock_guard
是沒有用的。 sync
是一個局部變量,因此它將超出范圍並在BlockStart()
退出時釋放互斥BlockStart()
。 只有在互斥鎖被鎖定時實際上執行了某些操作時,才有意義使用它,例如:
void BlockStart() noexcept
{
std::lock_guard<std::mutex> sync(lock);
// do something here while the mutex is locked...
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.