异常没有使用boost :: future / boost :: promise在线程之间正确传播

时间:2012-11-05 05:47:36

标签: c++ multithreading exception boost future

我已经简化了以下代码:

线程二:

  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异常或其派生的异常之一从线程2传播到线程1,而是获得以下内容:

  

在抛出一个实例后终止调用   '推动:: exception_detail :: clone_impl'
  what():std :: exception

似乎这个人有类似的麻烦,没有答案:

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()'

的匹配函数

只需返回一个布尔值,我就可以在没有异常的情况下正常运行代码,但这是一种妥协。

1 个答案:

答案 0 :(得分:0)

我会尝试在你的主题二中做类似的事情:

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

否则,如果您希望current_exception()能够正常工作,则必须处理以下内容:

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