简体   繁体   English

OpenMP 无法使用 map 迭代器并行化 for 循环

[英]OpenMP can't parallelize for loop with map iterator

The code is as follows.代码如下。

int main()
{
    map<int,int> a;
    for (int i = 0; i < 6; i++)
    {
        a.insert(make_pair(i, i+1));
    }
    
    map<int,int>::iterator it;
#pragma omp parallel for default(none) shared(a)
    for (it = a.begin(); it != a.end(); it++)
    {
        printf("the first is %d\n", it->first);
    }
    return 0;
}

the code compilation fails.代码编译失败。 But I can use vector iterator, the code is as follows:但是我可以使用向量迭代器,代码如下:

    int main()
    {
            vector<int> vec(23,1);
            vector<int>::iterator it;
            // map<int,int>::iterator it;
#pragma omp parallel for default(none) shared(vec)
            for (it = vec.begin(); it < vec.end(); it++)
            {
                printf("the number is %d\n", *it);
            }
        return 0;
    }

the vector iterator can work correctly.How can I parallelize for loop with map iterator directly as the same way of using vector iterator?向量迭代器可以正常工作。我怎样才能像使用向量迭代器一样直接使用 map 迭代器并行化 for 循环? The newest OpenMP version (5.2) has been published, OpenMP website .最新的 OpenMP 版本(5.2)已经发布, OpenMP 网站 Can I do this by the newest OpenMP API?我可以通过最新的 OpenMP API 做到这一点吗?

The iterator for a std::map is not a random-access-iterator , so it cannot be used as the control variable in an OpenMP parallel for loop. std::map的迭代器不是random-access-iterator ,因此它不能用作 OpenMP 并行 for 循环中的控制变量。 The iterator for a std::vector is a random access iterator, so it can be used. std::vector的迭代器是随机访问迭代器,因此可以使用。

The random access is necessary so that the OpenMP runtime can quickly advance the loop counter for each thread to its proper initial value (and the later iteration values it will compute for that thread).随机访问是必要的,以便 OpenMP 运行时可以将每个线程的循环计数器快速推进到其正确的初始值(以及稍后将为该线程计算的迭代值)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM