一旦调用std::future.get()
,它就会变得无效,因为调用future.valid()
将确认。以下代码段将在运行时失败,并显示错误 [g++ 4.7.0]:
terminate called after throwing an instance of 'std::future_error'
what(): No associated state
我正在尝试对 th1 和 th2 的依赖项进行编码,两者都在等待 th0 完成。
问题是不能从 2 个线程调用std::future.get()
。
我可以想到一些涉及condition_variable
的修复,或通过队列等传达结果。
- 什么是最佳/最有效的解决方案?
- 只需使用
condition_variable
和notify_all()
?
谢谢。
template<typename R>
class scheduler
{
public:
typedef R ret_type;
typedef std::function<R()> fun_type;
typedef std::promise<ret_type> prom_type;
typedef std::future<ret_type> fut_type;
// ...
private:
void init();
...
std::vector<prom_type> prom;
std::vector<fut_type> fut;
...
};
template<typename R>
scheduler<R>::init()
{
// ...
// set fut[i] = prom[i].get_future(), for each i
fun_type f0 = myFun0;
fun_type f1 = myFun1;
fun_type f2 = myFun2;
std::thread th0([this](fun_type f)
{
prom[0].set_value(f0());
},f0)
std:thread th1([this](fun_type f, R fut_val)
{
prom[1].set_value(f1());
},f1,fut[0].get());
std::thread th2([this](fun_type f, R fut_val)
{
prom[2].set_value(f2());
},f2,fut[0].get());
// Join on threads : th0.join(), etc.
}
您应该考虑为此使用 shared_future
。
类模板 std::shared_future 提供了一种访问异步操作结果的机制,类似于 std::future,不同之处在于允许多个线程等待相同的共享状态。如果每个线程通过自己的shared_future对象副本访问同一共享状态,则从多个线程访问同一共享状态是安全的。