1

I would like to use the task pragmas of openMP for the next code:

std::vector<Class*> myVectorClass;
#pragma omp parallel
{
    #pragma omp single nowait
    {
        for (std::list<Class*>::iterator it = myClass.begin(); it != myClass.end();) {
           #pragma omp task firstprivate(it) 
                (*it)->function(t, myVectorClass)) 
            ++it;
        }
    }
    #pragma omp taskwait
}

The problem, or one of them, is that the myVectorClass is a pointer to an object. So it is not possible to set this vector as shared. myVectorClass is modified by the function. The previous code crash. So, could you tell me how to modify the previous code (without using the for-loop pragmas)?

Thanks

Mysticial
  • 464,885
  • 45
  • 335
  • 332
smc
  • 53
  • 1
  • 6

1 Answers1

1

myVectorClass is a vector of pointers. In your current code, you set it as shared. Since your code crashes, I suppose you changes the length of myVectorClass in function(). However std::vector is not thread-safe, so modifying the length in multiple threads will crash its data structure.

Depending on what exactly function() does, you could have simple solutions. The basic idea is to use one thread-local vector per thread to collect the result of function() first, then concatenate/merge these vectors into a single one.

The code shown here gives a good example.

C++ OpenMP Parallel For Loop - Alternatives to std::vector

std::vector<int> vec;
#pragma omp parallel
{
    std::vector<int> vec_private;
    #pragma omp for nowait //fill vec_private in parallel
    for(int i=0; i<100; i++) {
        vec_private.push_back(i);
    }
    #pragma omp critical
    vec.insert(vec.end(), vec_private.begin(), vec_private.end());
}
Community
  • 1
  • 1
kangshiyin
  • 9,681
  • 1
  • 17
  • 29
  • Thanks, it works. However I have other issue with the iterators. I will write a new post. – smc Oct 30 '13 at 18:39