C 异步 Future(递延vs async)
C++ async + future (deferred vs async)
这是我正在使用的测试程序。有人可以详细描述该输出的发生的原因和原因吗?
为什么launch::async
将g_num
的值作为0
获取,而launch::deferred
获取100
?
launch::async
和launch::deferred
都有main
堆栈上的arg
的正确值,我相信这意味着他们都应该获得100
。
代码:
#include <iostream>
#include <future>
using namespace std;
thread_local int g_num;
int read_it(int x) {
return g_num + x;
}
int main()
{
g_num = 100;
int arg = 1;
future<int> fut = async(launch::deferred, read_it, arg);
arg = 2;
future<int> fut2 = async(launch::async, read_it, arg);
cout << "Defer: " << fut.get() << endl;
cout << "Async: " << fut2.get() << endl;
return 0;
}
输出:
Defer: 101
Async: 2
文档指出launch::deferred
将在调用线程上调用函数,而launch::async
将在新线程上调用该函数。
对于调用线程,g_num
的值是您将其设置为MAIN的任何内容。对于一个新线程,该值是值initialized(0
的int
(,因为您从未设置它。感谢@milesbudnek的更正。
g_num
被定义为 thread_local
,这意味着您应用中的每个线程都有其自己的 g_num
launch::deferred
在调用线程上运行。主线程上的g_num
更改为100。在使用launch::async
启动的线程上没有更改它,这是其值仍然是默认值的原因。
相关文章:
- 在VS代码中交叉编译Windows与Linux上的MinGW的SDL程序
- 如何为模板化对象创建模板向量?VS正在投掷C3203
- 数据成员SFINAE的C++17测试:gcc vs clang
- 为什么在Windows上的VS 2019和Clang 9中"size_t"在没有标题的情况下工作
- 在for循环中使用auto vs decltype(vec.size())来处理字符串的向量
- 为什么std::async使用同一个线程运行函数
- 正在VS调试器中监视映射条目
- Confusion: decltype vs std::function
- 将IBM Rhapsody模型集成到VS 2019中
- VS Code "command":"make"与终端窗口中的命令行"make"不同
- 使用VS Code和CMake Tools运行自定义命令
- 为什么可以将左值传递给"std::async",即使它引用了右值
- 修改 VS Code 中的默认C++代码段
- 如何使用c++在VS 2019上运行SQL查询
- vs 2015 constexpr变量不恒定,但与2019相比还好吗
- 使用用户定义的参数调用future/async并调用类方法
- C 异步 Future(递延vs async)
- C# Task.Run() vs. C++ std::async()
- std::async vs std::promise
- Async RestFul vs Websocket