首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >写入未排序向量的parallel_for

写入未排序向量的parallel_for
EN

Stack Overflow用户
提问于 2014-01-14 21:31:00
回答 1查看 154关注 0票数 0

我有一个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,因为我将它们与索引一起存储):

代码语言:javascript
运行
复制
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 anyway

indexList.size()应该是(units.size() + 1) * (units.size()/2),但它稍微少了一点。而一堆索引只是算法无法正确生成的零。那么,就这么简单,在parallel_for中写入共享向量是不可能的吗?

EN

回答 1

Stack Overflow用户

发布于 2014-01-15 04:13:10

除了@Yakk的建议和concurrent_vector,你也可以做到这一点。

代码语言:javascript
运行
复制
combinable<vector<patchIndex>> indexList;

//在循环中。

代码语言:javascript
运行
复制
indexList.local().push_back(currIndex);

//当超出循环时。

代码语言:javascript
运行
复制
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是性能更好还是可组合性更好。重点是要理解,我们也可以使用无锁容器来完成这项工作。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/21114817

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档