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 或通过队列传递结果等的修复方法。

谢谢。

 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

The class template std::shared_future provides a mechanism to access the result of asynchronous operations, similar to std::future, except that multiple threads are allowed to wait for the same shared state.... Access to the same shared state from multiple threads is safe if each thread does it through its own copy of a shared_future object.