0

Is it possible to fill out a boost::ptr_vector inside an OpenMP loop? The only way I can see how to add a 'new' entry to ptr_vector is via push_back(), which I assume is not thread safe.

See example below (gcc compilation: g++ ptr_vector.cpp -fopenmp -DOPTION=1). Currently only g++ ptr_vector.cpp -DOPTION=2 works.

#include <boost/ptr_container/ptr_vector.hpp>
#include <iostream>

#ifdef _OPENMP
#include <omp.h>
#endif

int main() {
        boost::ptr_vector<double> v;
        int n = 10;

#       if OPTION==1
        v.resize(n);
#       endif

        int i;
        #ifdef _OPENMP
        #pragma omp barrier
        #pragma omp parallel for private(i) schedule(runtime)
        #endif
#       if OPTION==1
        for ( i=0; i<n; ++i ) {
                double * vi = &v[i];
                vi = new double(i);
        }
#       elif OPTION==2
        for ( i=0; i<n; ++i )
                v.push_back(new double(i));
#       endif

        for ( size_t i=0; i<n; ++i )
                std::cout << "v[" << i << "] = " << v[i] << std::endl;
}

Thanks for any help!

psilouette
  • 83
  • 1
  • 6
  • 1
    http://stackoverflow.com/questions/18669296/c-openmp-parallel-for-loop-alternatives-to-stdvector/18671256#18671256 – Z boson Apr 18 '16 at 08:19

1 Answers1

0

To answer my own question, the solution is to use the replace() function:

    int i;
    #ifdef _OPENMP
    #pragma omp barrier
    #pragma omp parallel for private(i) schedule(runtime)
    #endif
    for ( i=0; i<n; ++i ) {
            v.replace(i,new double(i));
    }

seems to work for this example, but is this method thread safe in general?

psilouette
  • 83
  • 1
  • 6