Why a while loop in a parallel OMP section cannot end when the termination condition depends on an update from another section

Is the C ++ code below legal, or is there a problem with my compiler? The code was executed in a shared library using

gcc version 4.4.6 20110731 (Red Hat 4.4.6-3) (GCC)

and openMP, and then called through R 2.15.2.

int it=0; #pragma omp parallel sections shared(it) { #pragma omp section { std::cout<<"Entering section A"<<std::endl; for(it=0;it<10;it++) { std::cout<<"Iteration "<<it<<std::endl; } std::cout<<"Leaving section A with it="<<it<<std::endl; } #pragma omp section { std::cout<<"Entering section B with it="<<it<<std::endl; while(it<10) { 1; } std::cout<<"Leaving section B"<<std::endl; } } 

I get the following output (apologies for interlacing the output from 2 threads, but I think it is being interpreted):

 Entering section A Iteration Entering section B with it=0 0 Iteration 1 Iteration 2 Iteration 3 Iteration 4 Iteration 5 Iteration 6 Iteration 7 Iteration 8 Iteration 9 Leaving section A with it=10 

Then the program stops: section B seems to be stuck in a while loop. Since the variable 'it' is shared, I do not understand why the while loop does not end when section A is completed.

+6
source share
1 answer

This is because the shared variable means that it is the same for all threads, but the programmer still needs to synchronize access by hand

SHARED offer

It is the programmer's responsibility to ensure that multiple threads properly handle SHARED variables (e.g. through CRITICAL sections)

So, you can, for example, flush variables after completing the first section:

  #pragma omp section { std::cout<<"Entering section A"<<std::endl; for(it=0;it<10;it++) { std::cout<<"Iteration "<<it<<std::endl; } #pragma omp flush(it) std::cout<<"Leaving section A with it="<<it<<std::endl; } #pragma omp section { std::cout<<"Entering section B with it="<<it<<std::endl; while(it<10) { #pragma omp flush(it) 1; } std::cout<<"Leaving section B"<<std::endl; } 
+4
source

Source: https://habr.com/ru/post/943985/


All Articles