简体   繁体   中英

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? The newest OpenMP version (5.2) has been published, OpenMP website . Can I do this by the newest 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. The iterator for a std::vector is a random access iterator, so it can be used.

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).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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