简体   繁体   English

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

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

Once std::future.get() is called, it becomes invalid, as a call to future.valid() will confirm. 一旦调用了std::future.get() ,它将变为无效,因为对future.valid()的调用将确认。 The following code piece will fail at run-time with the error [g++ 4.7.0]: 以下代码段将在运行时失败并显示错误[g ++ 4.7.0]:

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

I'm trying to encode a dependency of th1 and th2 both waiting on completion of th0 . 我正在尝试编码th1th2的依赖关系,它们都在等待th0的完成。

The problem is that std::future.get() cannot be called from 2 threads. 问题是无法从2个线程调用std::future.get()

I can think of a couple of fixes involving condition_variable , or communicating results through a queue, etc. 我可以想到一些涉及condition_variable或通过队列传递结果等的修复。

  • What is the best/most efficient fix? 什么是最好/最有效的修复?
  • Just use a condition_variable and notify_all() ? 只需使用condition_variablenotify_all()

Thanks. 谢谢。

 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.
  }

You should consider using shared_future for this. 你应该考虑使用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. 类模板std :: shared_future提供了一种访问异步操作结果的机制,类似于std :: future,除了允许多个线程等待相同的共享状态....从多个访问相同的共享状态如果每个线程通过其自己的shared_future对象副本执行它,则线程是安全的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM