簡體   English   中英

std :: future.get()多次調用(來自不同的線程)

[英]std::future.get() Multiple Calls (from Different Threads)

一旦調用了std::future.get() ,它將變為無效,因為對future.valid()的調用將確認。 以下代碼段將在運行時失敗並顯示錯誤[g ++ 4.7.0]:

  terminate called after throwing an instance of 'std::future_error'
  what():  No associated state

我正在嘗試編碼th1th2的依賴關系,它們都在等待th0的完成。

問題是無法從2個線程調用std::future.get()

我可以想到一些涉及condition_variable或通過隊列傳遞結果等的修復。

  • 什么是最好/最有效的修復?
  • 只需使用condition_variablenotify_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對象副本執行它,則線程是安全的。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM