Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.
  }
like image 816
Charles Pehlivanian Avatar asked Jan 21 '16 14:01

Charles Pehlivanian


1 Answers

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.

like image 174
Ami Tavory Avatar answered Nov 13 '22 03:11

Ami Tavory