繁体   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