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.

有帮助吗?

解决方案 2

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>.

其他提示

It's the "choice" combination for tasks. You have a continuation (then), a join (when_all) and choice (when_any). The docs say ...

Creates a task that will complete successfully when any of the tasks supplied as arguments completes successfully.

See the task class and Asynchronous programming in C++ for more details. More discussion and examples.

Take for example:

task<string> tasks[] = {t1, t2, t3};
auto taskResult =  when_all (begin(tasks), end(tasks))
    .then([](std::vector<string> results) {

... is equivalent to ...

(t1 && t2 && t3).then

Whereas ...

task<string> tasks[] = {t1, t2, t3};
auto taskResult = when_any (begin(tasks), end(tasks))
    .then([](string result) {

... is equivalent to ...

(t1 || t2 || t3).then
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top