我遇到了一个使用案例,希望在std::future和Boost strand结合使用。
为了减少代码重复,我编写了一个通用函数,可以将任务发布到Boost strand并返回future。
// Some definitions first...
typedef boost::asio::io_service::strand cb_strand;
typedef std::shared_ptr< cb_strand > cb_strand_ptr;
代码大概长这个样子:
//////////////////////////////////////////////////////////////////////////
template <class Task>
auto post_future_to_strand(cb_strand_ptr apStrand, Task task)
{
using return_type = decltype(task());
auto promise = std::make_shared<std::promise<return_type>>();
auto future = promise->get_future();
apStrand->wrap
(
[promise, task]()
{
try
{
promise->set_value(task());
}
catch (...)
{
// LOG ERROR ...
// NOTE: Exceptions can be thrown when setting the exception!
try
{
promise->set_exception(std::current_exception());
}
catch (...)
{
//LOG ERROR ...
}
}
}
);
return future;
};
我希望您能够将以下示例中展示的内容发布到一个串中,该内容与IT技术相关。请润色并使其更加易于理解,但不要删除HTML标签。请按照格式要求仅返回翻译结果。
std::future<int> f = post_future_to_strand(m_apStrand, std::bind(&foo::bar, this))
std::cout << "foo::bar() -> int is " << f.get() << std::endl;
很遗憾,我遇到了运行时异常:
terminate called after throwing an instance of 'std::future_error'
what(): std::future_error: Broken promise
Signal: SIGABRT (Aborted)
我看完文档后,我认为我理解了什么是"broken promise"以及产生这种情况的原因;然而,我觉得我已经在lambda中捕捉了这个promise,所以一切都应该没问题。由于我是一个初学者,所以可能我的理解是错误的。
- Ubuntu Zesty
- GCC 6.3(使用cmake配置为C++14)