I would like to iterate through all elements in an std::list in parallel fashion using OpenMP. The loop should be able to alter the elements of the list. Is there a simple s
Without using OpenMP 3.0 you have the option of having all threads iterating over the list:
std::list::iterator it;
#pragma omp parallel private(it)
{
for(it = list1.begin(); it!= list1.end(); it++)
{
#pragma omp single nowait
{
it->compute();
}
}
}
In this case each thread has its own copy of the iterator (private) but only a single thread will access a specific element (single) whereas the other threads will move forward to the next items (nowait)
Or you can loop once to build a vector of pointers to be then distributed among threads:
std::vector< T*> items;
items.reserve(list.size());
//put the pointers in the vector
std::transform(list.begin(), list.end(), std::back_inserter(items),
[](T& n){ return &n; }
);
#pragma omp parallel for
for (int i = 0; i < items.size(); i++)
{
items[i]->compute();
}
Depending on your specific case one or the other can be faster. Testing which one suits you better is easy.