【问题标题】:parallel function call with async [duplicate]使用异步的并行函数调用 [重复]
【发布时间】:2017-02-23 13:48:26
【问题描述】:

需要在循环中创建和运行线程。这是编译/运行的代码,但它不会并行创建/运行线程,即形成此代码,我希望三个线程并行运行,而是每次调用函数 say依次发生。为什么?

 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 

【问题讨论】:

    标签: c++ multithreading asynchronous


    【解决方案1】:

    async 返回一个未来。根据http://en.cppreference.com/w/cpp/thread/future/~future

    它可能会阻塞 f 的结果,因为未来的析构函数会在 f 超出范围后调用

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-12-10
      • 2023-03-25
      • 1970-01-01
      • 2020-06-23
      • 1970-01-01
      • 1970-01-01
      • 2021-02-21
      相关资源
      最近更新 更多