繁体   English   中英

std :: async和std :: future行为

[英]std::async and std::future behaviour

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

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个线程似乎按顺序执行。 主线程块。

0: hello
1: hello
2: hello
.......
10000: hello
in 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

最后,尝试在返回的未来使用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将阻止future.get()。

引擎盖下究竟发生了什么?

异步返回的期货在他们的dtor中隐含地执行.wait() ,但是:这种行为可以move

这解释了你的所有症状。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM