Intel® C++ Compiler 16.0 User and Reference Guide

omp critical

Specifies a code block that is restricted to access by only one thread at a time.

Syntax

#pragma omp critical [name]

structured-block

Arguments

name

name of the critical section.

Description

When this the omp critical pragma is used, 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 sections are considered to have the same unspecified name.

Critical section names are global entities of the program.

The following example shows a queuing model in which a task is removed from the queue. To guard against multiple threads removing the same task from the queue, the operation to remove the task is placed in a critical section. Because there are two independent queues in this example, each queue is protected by these pragmas having different names, xaxis and yaxis, respectively:

Example

#include <omp.h>
int dequeue(work_queue *a);
void work(int i, work_queue *a);

void critical_example(work_queue *x, work_queue *y) {
  int ix_next, iy_next;

  #pragma omp parallel shared(x, y) private(ix_next, iy_next) {
    #pragma omp critical (xaxis)
    ix_next = dequeue(x);
    work(ix_next, x);

    #pragma omp critical (yaxis)
    iy_next = dequeue(y);
    work(iy_next, y);
  }
}