Search code examples
windows-8c++-cxppl

How does when_any work?


I have a std::vector< concurrency::task<void> > with a list of tasks that may or may not load in order. I came across the concurrency::when_any call, but don't know enough information about how to use it.

I came across this microsoft sample that uses the call (ScenarioInput1.xaml.cpp:100), but I don't understand the pair parameter, and how to adapt that to my return values.

Edit: What I'm trying to do:

struct TaskInfo {
  unsigned int                    uniqueId;
  concurrency::task<unsigned int> task;
};
typedef std::vector< TaskInfo > TaskList;
typedef std::vector< unsigned int > TaskReturns;


// Somewhere inside a class, tasks and finished are member variable.
TaskList tasks;
bool finished = false;

// Inside a member function of the same class as above
// Populate the tasks

concurrency::when_any( tasks.begin(), tasks.end() ).then([this](std::vector<unsigned int> ids){
  for( std::vector<unsigned int>::iterator list=ids.begin; list != ids.end(); ++ids ) {
    // a mutex lock would happen here
    for( TaskList::iterator allTasks = tasks.begin(); allTasks != tasks.end(); ++allTasks ) {
      if ( *list == allTasks->uniqueId ) { tasks.erase( allTasks ); break; }
    }
    // mutex unlock
    if ( tasks.size() == 0 ) { finished = true; break }
  }
}

// In another member function
if ( finished ) doOtherThings();

If what I'm trying to do is not as well thought out or not as efficient, please let me know.


Solution

  • Hans Passant provided this link which told me that when_any( ... ).then([]( <params> ) requires to be of the type std::pair<returnType, size_t index>.