C++ async + future(延迟vs异步)

Seo*_*oul 3 c++ multithreading asynchronous c++11 c++14

这是我正在使用的测试程序.有人可以详细描述正在发生的事情以及输出的原因.

为什么launch::async获得g_num价值0,而launch::deferred获得100.

双方launch::asynclaunch::differed得到了正确的价值观arg是在上main堆,我相信意味着他们应该有两个得到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;
    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;
}
Run Code Online (Sandbox Code Playgroud)

输出:

Defer: 101
Async: 2
Run Code Online (Sandbox Code Playgroud)

mer*_*011 5

文件指出,launch::deferred将调用调用线程的功能,同时launch::async将调用一个新的线程功能.

对于调用线程,值g_num是在main中设置的值.对于新线程,该值是值初始化(0for int),因为您从未设置它.感谢@MilesBudnek的纠正.