C ++异步仅使用2个内核 [英] C++ async only uses 2 cores
问题描述
我正在使用async同时运行一个方法,但是当我检查CPU时,它显示8个中只有2个正在使用.我的CPU利用率一直保持在13%-16%左右.异步函数应该在每次调用时创建一个新线程,因此应该可以使用更多处理器,或者我理解错误吗?
I am using async to run a method simultaneously, but when I check my CPU, it shows that only 2 of 8 are in use. My CPU utilization is about 13%-16% the whole time. The function async should create a new thread with every call and thus should be able to use more processors or did I understand something wrong?
这是我的代码:
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()会等待它完成,这之后似乎只是合乎逻辑的...
Thanks guys, I figured it out now. I didn't know, that calling .get() on the future would wait for it to finish, which afterwards seems only logical...
但是,我现在编辑了代码:
However, I edited my code now:
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能力.你救了我很多麻烦!再次感谢.
It works. Now it spawns threads properly and uses all my cpu power. You saved me a lot of trouble! Thanks again.
推荐答案
要回答潜在的问题:
您可能应该通过分割循环来重构代码.在第一个循环中,创建所有期货并将其放置在以 tmp
索引的地图中.在第二个循环中,您遍历该地图并获取每个将来的所有值,并将结果存储在 _paths
You probably should refactor the code by splitting the loop. In the first loop, you create all the futures and put them in a map indexed by tmp
. In the second loop, you loop over this map and get all the values from each future, storing the results in _paths
在第一个循环之后,您将有很多并行运行的期货,因此您的内核应该足够繁忙.如果 cells
足够大(> numCores),则最好拆分内部循环.
After the first loop, you'll have a lot of futures running in parallel, so your cores should be busy enough. If cells
is big enough (>numCores), it may be wise to just split the inner loop.
这篇关于C ++异步仅使用2个内核的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!