简体   繁体   中英

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. The following code piece will fail at run-time with the error [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 .

The problem is that std::future.get() cannot be called from 2 threads.

I can think of a couple of fixes involving condition_variable , or communicating results through a queue, etc.

  • What is the best/most efficient fix?
  • Just use a condition_variable and notify_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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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