我正在尝试向我的A Star Class添加异步方法。我希望能够异步计算Path,因此每个代理都可以独立于其他代理找到其路径。

问题是,目前看来,程序正在等待线程完成。
如何异步执行每个 call ?

功能

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);

我这是什么错

最佳答案

当您调用t1.get()时,您的代码正在等待计算结果。

启动任务时,您没有指定启动策略,因此您使用的是std::launch::async | std::launch::deferred的默认策略,该策略可能根本不会启动单独的线程,调用t1.get()时可能会被懒惰地评估。

您需要更改lambda以通过值而不是通过引用捕获,因为在执行lambda时,您引用的整数参数可能不再存在。

一个完整的工作示例是:

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();
}

关于c++ - std::async仅同步工作,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/53185372/

10-11 22:46
查看更多