2

This short code in below is based on the breath first search. I would hope to parallel it with OpenMP but have no success. Is there any way to have multiple threads inserting items to queue using OpenMP parallel construct ?


#include <omp.h>
#include <iostream>
#include <queue>

using namespace std;

int main(){

  queue<int> q;
  int v;
  int cnt = 0;

  for (int i =0; i<10; i++){
    q.push(i);
    cnt += 1;
  }

  while (!q.empty()) {
    v = q.front();
    q.pop();
    cout << "v=" << v << ",";

    #pragma omp parallel for
    for (int i = 1; i < 6; i++) {
      int j = v*i + 3;
      if ( j < 13) {
        q.push(j);
        cnt += 1;
      }
    }

  }

  cout << endl << q.size() << endl;
  cout << "count=" << cnt << endl;

  return 0;

}
Alexey Kukanov
  • 12,479
  • 2
  • 36
  • 55
user3658306
  • 217
  • 4
  • 15
  • std::queue::push is not thread safe, so it's not possible with queue –  Feb 01 '15 at 23:24

1 Answers1

3

Can std::queue concurrent insertion in OpenMP?

In general, NO. None of the standard containers are safe. You will have to provide external locks.

See this related question on Stack Overflow: Are there any concurrent containers in C++11?. Also see Concurrent Unordered Associative Containers for C++ from the working group and C++11 STL containers and thread safety from Stack Overflow.

Community
  • 1
  • 1
jww
  • 97,681
  • 90
  • 411
  • 885