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

标签 c++ multithreading c++11 asynchronous c++14

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

为什么launch::async获取g_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

最佳答案

documentation声明 launch::deferred 将在调用线程上调用该函数,而 launch::async 将在新线程上调用该函数。

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

关于C++ 异步 + future (延迟 vs 异步),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48918923/

相关文章:

java - Websphere WorkManager 加入多个线程

c - 在 POSIX 中执行线程

c++ - 使用getline时哪种方式更好?

c++ - std::thread 不是使用 Eclipse Kepler MinGW 的命名空间 std 的成员

c++ - 如何在 C++ 中删除集合或如何将集合的大小调整为 0

c++ - googletest 中的参数化和共享资源测试

c++ - 函数存储中的变量

c++ - popen 同时读写

c++ - Qt QObject::connect()函数无法连接

c# - 在 C# .NET 中管理多线程,控制每个操作的线程数