std::async and std::future behaviour

I am trying to understand the async behaviour and wrote some silly test programs.

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;
}

With the code as above, the output seems completely synchronous. All the 10000 threads seem to execute in sequence. The main thread blocks.

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

However, when the future being returned is stored in a vector, the output is all mangled and main exits without waiting for the spawned threads. Are the threads being detached here?

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;
}

The output:

2: hello3: hello

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

Finally, trying to use get() on the returned future still gives the similar mangled output:

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;
}

The output:

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

I would have thought in first case, the main will exit without waiting for the threads running in the background. And at least in 3rd scenario, main will block on the future.get().

What exactly is happening here under the hood?


Futures returned by async do a .wait() impliclitly in their dtor, but: this behaviour can be move ed.

Which explains all of your symptoms.

链接地址: http://www.djcxy.com/p/30822.html

上一篇: R不一致性:为什么add = T有时会起作用,有时不在plot()函数中?

下一篇: std :: async和std ::将来的行为