The CRITICAL directive restricts access to a block of code to only one thread at a time. It takes the following form:
A thread waits at the beginning of a critical section until no other thread in the team is executing a critical section having the same name. All unnamed CRITICAL directives map to the same name.
If a name is specified in the CRITICAL directive, the same name must appear in the corresponding END CRITICAL directive. If no name appears in the CRITICAL directive, no name can appear in the corresponding END CRITICAL directive.
Critical section names are global entities of the program. If the name specified conflicts with any other entity, the behavior of the program is undefined.
Examples
The following example shows a queuing model in which a task is dequeued and worked on. To guard against multiple threads dequeuing the same task, the dequeuing operation is placed in a critical section.
Because there are two independent queues in this example, each queue is protected by CRITICAL directives having different names, XAXIS and YAXIS, respectively:
c$OMP PARALLEL DEFAULT(PRIVATE) SHARED(X,Y)
c$OMP CRITICAL(XAXIS)
CALL DEQUEUE(IX_NEXT, X)
c$OMP END CRITICAL(XAXIS)
CALL WORK(IX_NEXT, X)
c$OMP CRITICAL(YAXIS)
CALL DEQUEUE(IY_NEXT,Y)
c$OMP END CRITICAL(YAXIS)
CALL WORK(IY_NEXT, Y)
c$OMP END PARALLEL