c++ - 主函数中任务的并行编程 - 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
}
}
比赛条件等不能发生。谢谢你的帮助!
解决方案
是的,您可以使用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();
}
(您会因此得到混乱的控制台输出,因为您需要使用互斥锁或其他类似资源来保护对控制台的访问。)
推荐阅读
- ruby - 如何更改 GEM 包管理器版本,而不是特定的 gem/module/package
- android - 在非标准构建类型的情况下,androidTest 依赖项的未解析符号
- r - 如何展平非原子函数结果,以便可以将其分配为 dplyr mutate 步骤的一部分?
- dictionary - 以字符串为键和任何值的字典
- python - 什么是线性池化层?
- angular - 我如何从角度组件调用 HTML 标记函数
- javascript - 如何从网站下载嵌入式视频?
- installation - LoadRunner 2020 安装中的致命错误
- python - 获取 IndexError:列表索引超出范围错误
- c# - 为什么图像没有输入变量?