c++ - 在 switch 语句中同步调用 C++ std::async
问题描述
我正在使用 c++,并且想做异步编程。我尝试了以下代码:
#include <thread>
#include <chrono>
#include <iostream>
#include <future>
void f(int id) {
switch (id) {
case 28: {
std::this_thread::sleep_for(std::chrono::milliseconds(1000));
break;
}
case 9: {
std::async(f, 28); //I am using std::async instead of std::thread because I want to get a return value from it in my real code
break;
}
}
std::cout << "Test For " << id << std::endl;
}
int main() {
f(9);
}
这打印
Test For 28
Test For 9
(整条消息在 1 秒后打印)我想要发生的是
Test For 9
Test For 28
(我希望这两条消息彼此相隔 1 秒打印)
然后我尝试在 100000 毫秒内完成,但同样的事情发生了(除了它需要更长的时间)。
这有没有发生的原因?
这也行不通
#include <thread>
#include <chrono>
#include <iostream>
#include <future>
int f(int id) {
switch (id) {
case 28: {
std::this_thread::sleep_for(std::chrono::milliseconds(100000));
break;
}
case 9: {
std::future<int> a = std::async(f, 28);
break;
}
}
std::cout << "Test For " << id << std::endl;
return 0;
}
int main() {
f(9);
}
因为它产生了相同的结果
解决方案
推荐阅读
- vb.net - 值不能为空。参数名称:图像
- node.js - 限制 Node.JS HTTP 服务器上的上传带宽
- qnx - QNX 7.0 的 Momentics 在哪里?
- flutter - 在 Flutter 中使用设置的 FPS 绘制大量简单、填充颜色的矩形的最高效方法是什么?
- java - 在循环中初始化双精度会给出错误“变量可能尚未初始化”
- angular - Angular 重新加载页面 ngSubmit
- python - python pandas数据框:将函数返回元组分配给数据框的两列
- postgresql - 使用物化视图改进 jsonb 索引和查询
- excel - 将数据透视表范围从一个工作表复制到另一个工作表。代码正在复制活动工作表数据
- matlab - 标题语法在 matlab 绘制图形和图表时出错