Are results of concurrency::when_all's return vector FIFO?

963 views Asked by At

Concurrency::when_all function returns a std::vector<T> with the return values of all tasks it awaited.

Are the values in the vector in any sort of order, or are they in the order in which the tasks completed?

1

There are 1 answers

0
user534498 On BEST ANSWER

I can't find from microsoft documentation either. Made a simple test, the thread ends with somehow a random order, but the final output is 1,2,3,4,5. You can create 100 threads with different random loads, I think result won't change. The conclusion is you can safely use it with this assumption.

#include <ppltasks.h>
#include <array>
#include <iostream>

using namespace concurrency;
using namespace std;

int wmain()
{
    // Start multiple tasks. 
    array<task<int>, 5> tasks =
    {
        create_task([]() -> int {
            for (int i = 0; i < 100; i++) {
                wcout << "thread 1: " << i << endl;
            }
            return 1; 
        }),
        create_task([]() -> int {
            for (int i = 0; i < 100; i++) {
                wcout << "thread 2: " << i << endl;
            }
            return 2; 
        }),
        create_task([]() -> int {
            for (int i = 0; i < 100; i++) {
                wcout << "thread 3: " << i << endl;
            }
            return 3; 
        }),
        create_task([]() -> int {
            for (int i = 0; i < 100; i++) {
                wcout << "thread 4: " << i << endl;
            }
            return 4; 
        }),
        create_task([]() -> int {
            for (int i = 0; i < 100; i++) {
                wcout << "thread 5: " << i << endl;;
            }
            return 5; 
        })
    };

    auto joinTask = when_all(begin(tasks), end(tasks)).then([](vector<int> results)
    {
        for_each(begin(results), end(results), [](int a) {
            wcout << a << endl;
        });
    });

    joinTask.wait();
}