【发布时间】:2018-08-01 19:15:15
【问题描述】:
这是我正在使用的测试程序。有人可以详细描述发生了什么以及此输出的原因吗?
为什么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
【问题讨论】:
-
尝试不使用
thread_local。
标签: c++ multithreading c++11 asynchronous c++14