简体   繁体   中英

Can I use a map iterator in parallel with OpenMP?

I try to parallelize a loop using a std::map<int, int> iterator with OpenMP. But I get the following error message:

error: invalid controlling predicate

My gcc vervion is 7.4, OpenMP version (maybe) over 4.0.

Can a std::map<int, int> iterator be used in parallel with OpenMP? THX!

#include <iostream>
#include <map>
#include <vector>

#include <omp.h>

using namespace std;

int main() {

    map<int, int> t;
    for(int i=0; i<100; i++) t[i]=i;

#pragma omp parallel for
    for (map<int, int>::iterator iter = t.begin(); iter != t.end(); iter++) {

        iter.operator*().second += 100;
        std::cout << iter.operator*().second << std::endl;
    }

    std::cout << "Hello, World!" << std::endl;
    return 0;
}

build with command:

g++ main.cpp -o main -fopenmp

Not directly. You can only use random access iterators with OpenMP loops.

Note that the error you receive relates to the use of != as relation operator. Technically this is possible since OpenMP 5.0, before you had to use <,<=,>=,> , but your approach still won't work correctly.

As long as you do not modify the map itself (only the stored values), you may use the following manual worksharing approach:

// note no "for"
#pragma omp parallel
{
    ssize_t i = 0;
    for (auto elem : t) {
        // in practice, store the result of these functions in local variables
        if (i++ % omp_get_num_threads() != omp_get_thread_num()) {
            continue; // only execute loops that this thread is responsible for
        }
        elem.second += 100;
        std::cout << elem.second << std::endl;
    }
}

Note that the output still may be unordered and overlapping , but that is another topic.

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