【问题标题】:Exception not propagating properly across threads using boost::future/boost::promise使用 boost::future/boost::promise 的异常未在线程间正确传播
【发布时间】:2012-10-24 23:06:52
【问题描述】:

我已经简化了以下代码:

线程二:

  boost::unique_future<void> future;
  TaskPtr task(new task::ReloadConfig(future));
  Listener::PushTask(task);
  future.wait();

  try
  {
    future.get();
  }
  catch (const cfg::ConfigError& e)
  {
    return cmd::Result::Okay;
  }

线程二:

  try
  {
    cfg::UpdateShared(std::shared_ptr<cfg::Config>(new cfg::Config(configFile)));
  }
  catch (...) // should be cfg::ConfigError
  {
    promise.set_exception(boost::current_exception());
    return;
  }

  promise.set_value();

我得到以下内容,而不是 Cfg::ConfigError 异常或其派生异常之一从线程二传播到线程一:

在抛出一个实例后调用终止 'boost::exception_detail::clone_impl'
什么():标准::异常

好像这个人也有类似的问题,没有答案:

https://stackoverflow.com/questions/10857834/how-to-use-boostfuture-get-to-get-user-defined-exception

如果我尝试使用 boost::enable_current_exception:也会收到以下错误:

/usr/local/include/boost/exception/exception.hpp:419:20:错误:否 调用'std::runtime_error::runtime_error()'的匹配函数

只要返回一个布尔值,我就可以让代码正常工作,没有异常,但这是一种折衷方案。

【问题讨论】:

    标签: c++ multithreading exception boost future


    【解决方案1】:

    我会尝试在你的线程二中做类似的事情:

    catch (const cfg::ConfigError& e)
    {
        promise.set_exception(boost::make_exception_ptr(e));
    }
    

    否则,如果你想让 current_exception() 工作,你必须搞砸类似的事情:

    throw boost::enable_current_exception(cfg::ConfigError("meh")); 
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-09-03
      • 1970-01-01
      • 1970-01-01
      • 2012-12-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-11-25
      相关资源
      最近更新 更多