首页 > 解决方案 > 主函数中任务的并行编程 - C++

问题描述

是否可以定义两个任务并让它们在 C++ 中并行工作?我发现了一些关于并行函数的东西,但不是关于主函数中的并行任务,比如:

int main()

  // task 1
  int a = 0;
  for(int i = 0; i < 150; i++){
      a++;
      std::cout << a << std::endl;
      // do more stuff
  }

  // task 2
  int b = 0;
  for(int i = 0; i < 150; i++){
      b++;
      std::cout << b << std::endl;
      // do more stuff
  }
}

比赛条件等不能发生。谢谢你的帮助!

标签: c++c++17

解决方案


是的,您可以使用std::async和 lambdas 并行运行这两者。这是一个例子:

int main()
{
  auto f1 = std::async(std::launch::async, [](){
  // task 1
  int a = 0;
  for(int i = 0; i < 10; i++){
      a++;
      std::cout << a << std::endl;
      // do more stuff
  }      
  });    

  auto f2 = std::async(std::launch::async, [](){
  // task 2
  int b = 100;
  for(int i = 0; i < 10; i++){
      b++;
      std::cout << b << std::endl;
      // do more stuff
  }
  });
                       
  f1.wait();
  f2.wait();
}

(您会因此得到混乱的控制台输出,因为您需要使用互斥锁或其他类似资源来保护对控制台的访问。)


推荐阅读