【发布时间】:2014-06-05 19:59:01
【问题描述】:
我正在使用异步同时运行一个方法,但是当我检查我的 CPU 时,它显示只有 8 个中的 2 个在使用中。我的 CPU 利用率一直在 13%-16% 左右。 函数 async 应该在每次调用时创建一个新线程,因此应该能够使用更多处理器,还是我理解错误?
这是我的代码:
for (map<string, Cell>::iterator a = cells.begin(); a != cells.end(); ++a)
{
for (map<string, Cell>::iterator b = cells.begin(); b != cells.end(); ++b)
{
if (a->first == b->first)
continue;
if (_paths.count("path_" + b->first + "_" + a->first) > 0)
{
continue;
}
tmp = "path_" + a->first + "_" + b->first;
auto future = async(launch::async, &Pathfinder::findPath, this, &a->second, &b->second, collisionZone);
_paths[tmp] = future.get();
}
}
我理解错了吗?
编辑:
谢谢大家,我现在明白了。我不知道,在未来调用 .get() 会等待它完成,这之后似乎是合乎逻辑的......
但是,我现在编辑了我的代码:
for (map<string, Cell>::iterator a = cells.begin(); a != cells.end(); ++a)
{
for (map<string, Cell>::iterator b = cells.begin(); b != cells.end(); ++b)
{
if (a->first == b->first)
continue;
if (_paths.count("path_" + b->first + "_" + a->first) > 0)
{
continue;
}
tmp = "path_" + a->first + "_" + b->first;
mapBuffer[tmp] = async(launch::async, &Pathfinder::findPath, this, &a->second, &b->second, collisionZone);
}
}
for (map<string, future<list<Point>>>::iterator i = mapBuffer.begin(); i != mapBuffer.end(); ++i)
{
_paths[i->first] = i->second.get();
}
它有效。现在它正确地产生线程并使用我所有的 cpu 功率。你给我省了很多麻烦!再次感谢。
【问题讨论】:
-
我很确定操作系统做出的决定(在语言级别)无法保证。
-
“我理解错了吗?” Yes, you did.
-
在生成
future之后,您就正在收获它。 -
^如果你不想“收获”它,你必须自己产生异步线程
标签: c++ multithreading asynchronous