我有一个parallel_for循环,它迭代一个大的向量,分析它的不同部分(所有可能的序列,1-2,1-3,1-4,2-3,2-4,等等)。并将关于这些部分的统计信息存储在另一个未排序的向量中(使用push_back)。然后在parallel_for循环结束后对该向量进行排序。这不可能吗?但我得到了奇怪的读数,产生的未排序向量的大小不正确,大约2%的必要迭代丢失(使用正常的for循环,一切都是正确的)。部分问题可能是parallel_for循环的工作负载不相等:例如,对于一个有100个成员的向量,外部循环的第一次运行必须遍历全部100个成员,而最后一次运行只需要从98-100,99-100开始。以下是代码的简化版本(我在循环中使用unsigned,因为我将它们与索引一起存储):
vector<patchIndex> indexList;
indexList.reserve(2000000);
parallel_for(unsigned(1), units.size(), [&](unsigned n)
{
for (unsigned j = 0; j != (units.size() - n); j++)
{
patchIndex currIndex;
for (auto it = units.begin() + n; it != units.begin() + (j + n + 1); it++)
{
//calculate an index from the (*it).something
}
//some more calculations of the index
indexList.push_back(currIndex);
}
});
sort(indexList.begin(), indexList.end(), [](patchIndex &a, patchIndex &b) {return a.index > b.index; });
// at this point Visual Studio says that "sort is ambiguous" but it compiles anywayindexList.size()应该是(units.size() + 1) * (units.size()/2),但它稍微少了一点。而一堆索引只是算法无法正确生成的零。那么,就这么简单,在parallel_for中写入共享向量是不可能的吗?
发布于 2014-01-15 04:13:10
除了@Yakk的建议和concurrent_vector,你也可以做到这一点。
combinable<vector<patchIndex>> indexList;//在循环中。
indexList.local().push_back(currIndex);//当超出循环时。
vector<patchIndex> result;
result.reserve(2000000);
indexList.combine_each([&](patchIndex x)
{
result.push_back(x);
});
sort(result.begin(), result.end()[](patchIndex &a, patchIndex &b) {return a.index > b.index; });我还没有测试过使用concurrent_vector是性能更好还是可组合性更好。重点是要理解,我们也可以使用无锁容器来完成这项工作。
https://stackoverflow.com/questions/21114817
复制相似问题