c++ - 将 std::async 与 std::launch::async 一起使用时的奇怪行为
问题描述
我正试图绕过std::async
并std::futures
在 C++11 中引入。
#include <iostream>
#include <list>
#include <functional>
#include <vector>
#include <algorithm>
#include <thread>
#include <unistd.h>
#include <string>
#include <future>
using namespace std;
int hog_cpu()
{
cout << "hog_cpu" << endl;
volatile unsigned long long i = 0;
for(i = 0; i < 1000000000ULL ; i++);
return 50;
}
int hog_cpu_ex()
{
cout << "hog_cpu_ex" << endl;
volatile unsigned long long i = 0;
for(i = 0; i < 1000000000ULL ; i++);
return 500;
}
int main()
{
cout << "start threads asynchronously" << endl;
std::future<int> f1 = std::async(std::launch::async, hog_cpu);
std::future<int> f2 = std::async(std::launch::async, hog_cpu_ex);
cout << "Get the Results" << endl;
int r1 = f1.get();
int r2 = f2.get();
cout << "result 1: " << r1 << endl;
cout << "result 2: " << r2 << endl;
return 0;
}
我得到的上述程序的输出如下所示。
start threads asynchronously
Get the Results
hog_cpu_ex
hog_cpu
result 1: 50
result 2: 500
Process finished with exit code 0
我的问题是因为我使用std::launch::async
执行应该立即使用另一个线程开始。输出告诉我它打印了该行Get the results
,然后才开始执行。(从上面的日志中可以明显看出)。也hog_cpu_ex
开始前hog_cpu
。有人可以解释为什么会发生这种情况。
解决方案
当你这样做
std::future<int> f1 = std::async(std::launch::async, hog_cpu);
std::future<int> f2 = std::async(std::launch::async, hog_cpu_ex);
你又启动了两个执行线程。然后主线程在它调用每一行之后继续运行,直到它命中才会停止
int r1 = f1.get();
如果f1
还没有完成。由于主线程继续运行并且启动线程需要一些时间,因此Get the Results
在线程启动之前查看打印是非常合理的。
至于为什么看到
hog_cpu_ex
hog_cpu
而不是相反是由于您的操作系统。它可以控制哪些线程运行以及何时运行,因此它很有可能f1
进入睡眠状态,有空间f2
让它开始运行,然后在此之后f1
的某个时间启动。
推荐阅读
- python - 即使设置了所需的标头,Python 请求也会返回 403 错误代码
- html - 使用 CSS: lang() 选择器来切换 div 的可见性
- c# - C# 的 While 循环语法,我做错了什么?
- swift - 有没有办法减少 Swift 代码行的数量?
- scala - 为什么 Spark DataFrame 转换为 RDD 需要完全重新映射?
- html - 如何删除表单域之间的垂直间距?
- javascript - Javascript Promise.all 增加这个函数的速度
- maven - Azure DevOps:将 Maven 工件从 Azure 工件导入发布时出错
- wordpress - 网站的变化是通过IP地址而不是通过域名反映的
- amazon-dynamodb - AppSync 查询解析器:是否需要 expressionNames 和 expressionValues?