c++ - std::async 和 std::future 行为

标签 c++ c++11

我试图理解异步行为并编写了一些愚蠢的测试程序。

int f(int i)
    {
        std::cout << i << ": hello" << std::endl;
        int j = 0;
        while (j < 10000) //just add some delay
        {
            j++;
        }
        return j;
    }

int main()
{
    for (int i = 0; i < 10000; i++)
    {
        std::async(std::launch::async, f, i);
    }
    std::cout << "in main" << std::endl;
}

使用上面的代码,输出似乎是完全同步的。所有 10000 个线程似乎都按顺序执行。主线程 block 。

0: hello
1: hello
2: hello
.......
10000: hello
in main

但是,当返回的 future 存储在 vector 中时,输出全部被破坏并且 main 退出而不等待生成的线程。线程是否在此处分离?

int main()
{
    std::vector<std::future<int>> v;

    for (int i = 0; i < 10000; i++)
    {
        v.push_back(std::move(std::async(std::launch::async, f, i)));
    }

    std::cout << "in main" << std::endl;
}

输出:

2: hello3: hello

46: hello
: hello5: hello
9: hello
10: hello
11: hello

最后,尝试在返回的 future 上使用 get() 仍然会给出类似的错误输出:

int main()
{
    std::vector<std::future<int>> v;

    for (int i = 0; i < 10000; i++)
    {
        v.push_back(std::move(std::async(std::launch::async, f, i)));
    }

    for (int i = 0; i < 10000; i++)
    {
        std::cout << v[i].get();    
    }

    std::cout << "in main" << std::endl;
}

输出:

3: hello
4: hello
1: hello
5: hello
0: hello
2: hello

我会想到在第一种情况下,main 将退出而不等待后台运行的线程。至少在第三种情况下,main 将阻塞在 future.get() 上。

幕后到底发生了什么?

最佳答案

异步返回的 Future 在它们的 dtor 中隐含地执行 .wait(),但是:此行为可以被移动

这可以解释您的所有症状。

关于c++ - std::async 和 std::future 行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37369259/

相关文章:

c++ - ACM Jolly 跳线 2

c++ - 无法理解这种基本的线程行为

c++ - 为什么 enable_shared_from_this 有一个非虚拟析构函数?

c++ - 以非顺序顺序在 vector 中分配值

c++ - 这个列表是垃圾内存吗?

c++ - 正 lambda : '+[]{}' - What sorcery is this?

c++ - SFINAE 重载,必须考虑哪些规则

c++ - 在声明时定义vector of vector of vector的大小

c++ linux - 从IP获取接口(interface)

c++ - 如何返回重载二元运算符的值