user11246552
user11246552

Reputation:

How do I declare an async function?

I am new to threads and async functions and I am trying use async function to return information from the function below:

std::vector<std::vector<int> > calculatingSlices(SquareMatrix A, std::vector<std::vector<int> > slices)

and I am doing this using the following code:

std::vector<std::vector<int>> slices;
std::vector<std:future<std::vector<int>>> results;
for(int i = 0; i < numOfThreads; i++){
    results.push_back(std::async(std::launch::async, calculatingSlices, A, slices))
}

I am getting this error though:

error: attempt to use a deleted function

So I guess my initial question is how do you declare an async function?

I also have a few questions about how async functions work. If you're declaring a number of async functions in a loop, like I have done above, will these all run simultaneously? or will they run one at a time as it progresses through the loop?

If they run one at a time, what would be a better way to run this function simultaneously amongst a varying number of threads?

Upvotes: 0

Views: 101

Answers (1)

KamilCuk
KamilCuk

Reputation: 141010

  1. Please post full message errors. The error you posted gives no hint whatsoever to the error.

  2. Please post compilable and fully reproducible MCVE.

  3. The compilation error by gcc is pretty clear:

<source>:14:87: error: no matching function for call to 'std::vector<std::future<std::vector<int> >
>::push_back(std::future<std::vector<std::vector<int> > >)'

         results.push_back(std::async(std::launch::async, calculatingSlices, A, slices))

As the return value of calculatingSlices is vector<vector>, you want to store vector<future<vector<vector>>> not vector<future<vector>>>. The function returns a 2d vector, not 1d.

So change:

std::vector<std:future<std::vector<int>>> results;

into

std::vector<std::future<std::vector<std::vector<int>>>> results;

Upvotes: 1

Related Questions