我正在实现一个树数据结构和一些对它的操作。每个节点都有一些值,指向其父节点的指针和子节点的列表。我实现了一个函数max_value,它递归地遍历树并找到存储在节点中的最大值。现在,我想使用C++11标准实现一个异步函数,它可以做同样的事情。我有以下代码:
template<typename T>
T Node<T>::max_value_async(void)
{
T current_value = p_value;
list<future<T>> results;
//launch tasks
for ( auto x : p_children)
{
results.insert(async(std::launch::async, x.max_value));
}
//wait for results
for (auto r : results)
r.wait();
//find highest value
for (auto r : results)
{
if (current_value < r.get())
current_value = r.get();
}
return current_value;
}但我在启动异步功能时遇到了麻烦。怎么了?
发布于 2012-10-27 18:15:15
有几个问题:
wait(),因为get()暗示了这一点。list或vector都可以很好地与push_back配合使用。您为list::insert提供了错误的参数数量。最好的方法是在emplace_back.get()。对get()的后续调用产生std::future_error错误异常。完整示例:
// g++ -pthread -std=c++0x
#include <iostream>
#include <future>
#include <list>
struct X {
X(int v) : mv(v) {}
int mv;
int max_value() const {
return mv;
}
};
int main(){
std::list<std::future<int> > results;
X x4(4);
X x5(5);
X x3(3);
results.emplace_back(std::async(std::launch::async,
[&x4](){ return x4.max_value();}));
results.emplace_back(std::async(std::launch::async,
[&x5](){ return x5.max_value();}));
results.emplace_back(std::async(std::launch::async,
[&x3](){ return x3.max_value();}));
// for sure there's better ways to do this step, but for clarity:
int best_value=0;
for (auto &r : results){
auto this_value=r.get();
if (best_value < this_value)
best_value = this_value;
}
std:: cout << best_value << std::endl;
}由于您使用的是共享指针,因此您还可以让lambda通过值获取对象,
std::shared_ptr<SomeT> some_obj= ... from somewhere... ;
results.emplace_back(
std::async(
std::launch::async, [some_obj](){ return some_obs->max_value();}
)
);https://stackoverflow.com/questions/13098484
复制相似问题