0

need to create and run threads, in a loop. Here is the code, which compiles/runs, but it does not create/run threads in parallel, i.e. form this code, I'd expect three threads run in parallel, but instead each call of function say happens in sequence. Why?

 template<typename T>
 void say(int n, T t) { 
  cout << " say: " << n << std::flush;
  for(int i=0; i<10; ++i) {
    cout << " " << t << std::flush;
 std::this_thread::sleep_for(std::chrono::milliseconds(1000));
  } cout << " end " << std::flush << endl;
}

 template<typename F, typename... Ts>
 inline auto reallyAsync(F&& f, Ts&&... params){
  return std::async(
      std::launch::async,
      std::forward<F>(f),
      std::forward<Ts>(params)...);
}

 int main() {
  float x = 100;

  for(int i=0; i<3; ++i) {
    auto f = reallyAsync(&say<decltype(x)>, i, x*(i+1)) ;
  }
}


output:
 say: 0 100 100 100 100 100 100 100 100 100 100 end 
 say: 1 200 200 200 200 200 200 200 200 200 200 end 
 say: 2 300 300 300 300 300 300 300 300 300 300 end 
user3081218
  • 79
  • 2
  • 7

1 Answers1

1

async returns a future. According to http://en.cppreference.com/w/cpp/thread/future/~future

it might be blocking on the result of f because of the future destructor, which would be called after f goes out of scope