一旦調用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
呃是的,這似乎是我想要的。我會嘗試... –