What is the correct way to use hpx::when_any function?

89 views Asked by At

I have just started learning parallel programming in c++ and wanted to use HPX for it. I need to complete several tasks in groups of N and I wanted to write code that puts all the threads into a vector and when at least one is done replace it with the next thread.

#include <iostream>
#include <vector>
#include "hpx/hpx_main.hpp"
#include "hpx/future.hpp"

using namespace std;



int dummy(int a){
    return a;
    }
    
int main(){
    vector<hpx::future<int>>futures;
    futures.reserve(3);
    
    for(int step = 0; step < 3; step++){
        futures.push_back(hpx::async(dummy, step));
        }
    
    int index;
    auto f2 = hpx::when_any(futures).then([&](auto f){
        return f;
        });
        
    
    auto res = f2.get();
    vector<hpx::future<int>> fut3 = res.futures;
    for(int i = 0; i < fut3.size(); i++){
        cout << fut3[i].get() << endl;
        }
    }

This code results in a following error:

error: static assertion failed: result type must be constructible from input type

I have tryied to find solutions online, but there is barely any examples of code with hpx.

1

There are 1 answers

0
gonidelis On

Try adding std::move when copying the resulting futures:

std::vector<hpx::future<int>> fut3 = std::move(res.futures);

The problem is that res.futures is invalidaded after the copy.