【问题标题】:std::thread created thread not handling exceptionsstd::thread 创建的线程不处理异常
【发布时间】:2014-02-27 06:33:18
【问题描述】:

我正在创建一些将被分离的 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 启动线程来处理异常?

【问题讨论】:

  • 您能否提供一个完整的、可编译的示例来演示该问题?

标签: c++ multithreading c++11


【解决方案1】:

根据这个问题的答案: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);
    ...

【讨论】:

    【解决方案2】:

    单独调用throw 会重新抛出当前异常,但这仅在catch 块内调用时有效。如果您尝试在没有当前异常的情况下在 try 块内单独调用 throw,则会调用 terminate() 并且您的应用程序会死掉。您必须告诉throw WHATtry 块内抛出,例如:

    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() 退出时,它会超出范围并释放互斥锁。只有在互斥锁被锁定时它确实做了一些事情时才有意义使用它,例如:

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

    【讨论】:

      猜你喜欢
      • 2017-05-13
      • 2012-04-14
      • 1970-01-01
      • 2013-09-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-08-06
      相关资源
      最近更新 更多