I wanted to parallelize this code with the help of OpenMP with something like
#pragma omp parallel for to divide the work amongst the different threads.
What would be an efficient way? Here level is shared between the varioud threads.
Here make is a set.
for(iter=make.at(level).begin();iter!=make.at(level).end();iter++)
{
Function(*iter);
}
If the type returned by
make.at(level)has random-access iterators with constant access time and if your compiler supports recent enough OpenMP version (read: it is not MSVC++) then you can directly use theparallel forworksharing directive:If the type does not provide radom-access iterators but still your compiler supports OpenMP 3.0 or newer, then you can use OpenMP tasks:
Here a single thread executes the for loop and creates a number of OpenMP tasks. Each task will make a single call to
Function()using the corresponding value of*iter. Then each idle thread will start picking from the list of unfinished tasks. At the end of the parallel region there is an implicit barrier so the master thread will dutifully wait for all tasks to finish before continuing execution past the parallel region.If you are unfortunate enough to use MS Visual C++, then you don’t have much of a choice than to create an array of object pointers and iterate over it using a simple integer loop:
It’s not the most elegant solution but it should work.
Edit: If I understand correctly from the title of your question, you are working with sets. That rules out the first algorithm since sets do not support random-access iterators. Use either the second or the third algorithm depending on your compiler’s supports for OpenMP tasks.