2014-02-27 115 views
0

我正在創建幾個將被分離的std :: threads。我想讓這些運行很長時間,並希望它們自己處理異常。std ::線程創建的線程沒有處理異常

我創建使用的std ::線程(功能)線程和釋放互斥體之前都要求分離並在功能並執行以下操作:

void BlockStart() noexcept { 
    std::lock_guard<std::mutex> sync(lock); 
} 
void Function() 
{ 
    BlockStart(); 
    try 
    { 
     throw; 
    } 
    catch(...) 
    { 
     std::cerr << "Caught something...\n"; 
    } 
} 

每次我運行此代碼,異常處理程序不被調用。 std :: terminate()的默認處理程序被調用,它調用中止。

如何獲得一個std ::線程啓動線程來處理異常?

+0

您能否提供一個完整的可編譯示例來演示該問題? –

回答

3

基於這一問題的答案: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); 
    ... 
1

調用本身throw重新拋出當前異常的鎖定擋板鎖,但是,只有catch塊內調用時的作品。如果您嘗試在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; 
    } 
} 

此外,使用std::lock_guard內的BlockStart()是沒用的。 sync是一個局部變量,因此當BlockStart()退出時,它將超出範圍並釋放互斥量。只有在互斥鎖被鎖定的情況下,它纔會有意義,例如:

void BlockStart() noexcept 
{ 
    std::lock_guard<std::mutex> sync(lock); 
    // do something here while the mutex is locked... 
}