一旦调用std::future.get()
,它将变为无效,因为future.valid()
的调用将被确认。下面的代码块将失败在运行时错误[克++ 4.7.0]:std :: future.get()多个呼叫(来自不同的线程)
terminate called after throwing an instance of 'std::future_error'
what(): No associated state
我试图编码TH1和TH2的依赖于TH0完成两个等待。
问题是std::future.get()
不能从2个线程中调用。
我能想到的一对夫妇涉及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.
}
'std :: shared_future'? – cpplearner
呃是的,这似乎是我想要的。我会尝试... –