The CRITICAL directive specifies a region of code that must be executed by only one thread at a time.
!$OMP CRITICAL [ name ] block !$OMP END CRITICAL [ name ]
#pragma omp critical [ name ] newline structured_block
If a thread is currently executing inside a CRITICAL region and another thread reaches that CRITICAL region and attempts to execute it, it will block until the first thread exits that CRITICAL region.
The optional name enables multiple different CRITICAL regions to exist:
Names act as global identifiers. Different CRITICAL regions with the same name are treated as the same region. All CRITICAL sections which are unnamed, are treated as the same section.
It is illegal to branch into or out of a CRITICAL block.
Fortran only: The names of critical constructs are global entities of the program. If a name conflicts with any other entity, the behavior of the program is unspecified.
All threads in the team will attempt to execute in parallel, however, because of the CRITICAL construct surrounding the increment of x, only one thread will be able to read/increment/write x at any time.
PROGRAM CRITICAL INTEGER X X = 0 !$OMP PARALLEL SHARED(X) !$OMP CRITICAL X = X + 1 !$OMP END CRITICAL !$OMP END PARALLEL END
#includemain() { int x; x = 0; #pragma omp parallel shared(x) { #pragma omp critical x = x + 1; } /* end of parallel section */ } </pre>