C 异步 Future(递延vs async)

C++ async + future (deferred vs async)

本文关键字:vs async 递延 异步 Future      更新时间:2023-10-16

这是我正在使用的测试程序。有人可以详细描述该输出的发生的原因和原因吗?

为什么launch::asyncg_num的值作为0获取,而launch::deferred获取100

launch::asynclaunch::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(0int(,因为您从未设置它。感谢@milesbudnek的更正。

g_num被定义为 thread_local,这意味着您应用中的每个线程都有其自己的 g_num

的副本

launch::deferred在调用线程上运行。主线程上的g_num更改为100。在使用launch::async启动的线程上没有更改它,这是其值仍然是默认值的原因。