c++ - 使用 async 的并行函数调用

标签 c++ multithreading asynchronous

<分区>

需要在循环中创建和运行线程。这是编译/运行的代码,但它不会并行创建/运行线程,即形成此代码,我希望三个线程并行运行,而是每次调用函数 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 

最佳答案

异步返回一个 future 。根据http://en.cppreference.com/w/cpp/thread/future/~future

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

关于c++ - 使用 async 的并行函数调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42417618/

相关文章:

java - 任务返回时运行监听器

javascript - GMaps JS 地理编码 : Using/Passing Variables With Asynchronous Geocode Function?

c++ - 设置每个像素的最快方法

c++ - C++ 中命名空间别名的范围是什么?

java - 如何使用 Java 将线程委托(delegate)给多个服务器并跟踪哪个线程位于哪个服务器上

c# - Task.StartOrRestartWhenPossible

json - 错误类型 '_InternalLinkedHashMap<String, dynamic>'不是 'String'类型的子类型

c++ - 使用重新解释转换将结构或类保存到文件

c++ - 如何使用 Clang 指定 C++17 中 utf-16 字符串文字的字节序?

C++ boost 线程 : Passing a method of an object