std :: future.get()多个调用(来自不同的线程)

Cha*_*ian 4 c++ multithreading future c++11

一旦std::future.get()被调用,它将变为无效,因为对的调用future.valid()将确认。以下代码段将在运行时失败,并显示错误[g ++ 4.7.0]:

  terminate called after throwing an instance of 'std::future_error'
  what():  No associated state
Run Code Online (Sandbox Code Playgroud)

我正在尝试编码th1th2的依赖项,它们都在th0完成时等待。

问题是std::future.get()不能从2个线程调用。

我可以想到一些涉及的修复程序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.
  }
Run Code Online (Sandbox Code Playgroud)

Ami*_*ory 7

您应该考虑shared_future为此使用。

类模板std :: shared_future提供了一种访问异步操作结果的机制,类似于std :: future,不同之处在于允许多个线程等待相同的共享状态。...从多个访问相同的共享状态如果每个线程都通过其自己的shared_future对象副本进行操作,则线程是安全的。

  • @查尔斯号 每个线程必须具有其共享状态相同的shared_future副本:OP中的上述代码用future替换为shared future无效。 (3认同)