MThiele
MThiele

Reputation: 387

std::async works only synchronously

im trying to add a async method to my A Star Class. I want to be able to calculate the Path asynchronously, so every agent is able to find his path independent from the other agents.

The problem is, at the moment it seems like that the programm is waiting until the thread has finished. How can i execute every call asynchronously?

Function

bool simplePath::navAgent::findPathAsync(int _startX, int _startY, int _endX, int _endY){
    auto t1 = std::async([&]{return this->findPath(_startX,_startY,_endX,_endY);});
    t1.get();
    return true;
}

Call

navComponent->findPathAsync(0,2,30,45);
    navComponent->findPathAsync(0,2,123,100);
    navComponent->findPathAsync(0,2,8,7);
    navComponent->findPathAsync(0,2,8,7);
    navComponent->findPathAsync(0,2,8,7);
    navComponent->findPathAsync(0,2,8,7);
    navComponent->findPathAsync(0,2,8,7);

What is my mistake here?

Upvotes: 1

Views: 111

Answers (1)

Alan Birtles
Alan Birtles

Reputation: 36498

When you call t1.get() your code is waiting for the result to be calculated.

When you launch your tasks you aren't specifying a launch policy so you are using the default policy of std::launch::async | std::launch::deferred which may not launch a separate thread at all and could just be lazily evaluated when you call t1.get().

You need to change your lambda to capture by value rather than by reference as the integer parameters you are referencing may no longer exist when your lambda is executed.

A fully working example would be:

std::future<bool> simplePath::navAgent::findPathAsync(int _startX, int _startY, int _endX, int _endY){
    return std::async(std::launch::async, []{return this->findPath(_startX,_startY,_endX,_endY);});
}

std::vector< std::future_bool > results;
results.emplace_back(navComponent->findPathAsync(0,2,30,45));
results.emplace_back(navComponent->findPathAsync(0,2,123,100));
results.emplace_back(navComponent->findPathAsync(0,2,8,7));
results.emplace_back(navComponent->findPathAsync(0,2,8,7));
results.emplace_back(navComponent->findPathAsync(0,2,8,7));
results.emplace_back(navComponent->findPathAsync(0,2,8,7));
results.emplace_back(navComponent->findPathAsync(0,2,8,7));

bool result = true;
for ( auto& f : results )
{
    result &= f.get();
}

Upvotes: 2

Related Questions