0

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?

David Božjak
  • 14,847
  • 15
  • 63
  • 97
  • I never used ppl, but from what microsoft's proposal to c++ standard, see the http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2013/n3558.pdf, and look for the when_all proposal, I think there's no technical difficulty to implement the result order as same as the input task order. So I guess it's not FIFO. – user534498 Jan 09 '14 at 09:15
  • It would really be good for my use case if it were not FIFO. But would like to see it documented somewhere before relying on it. – David Božjak Jan 09 '14 at 10:49

1 Answers1

2

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();
}
user534498
  • 3,596
  • 2
  • 22
  • 45