Intel® Advisor User Guide

ID 766448
Date 11/07/2023
Public

A newer version of this document is available. Customers should click here to go to the newest version.

Document Table of Contents

OpenMP Critical Sections

Use OpenMP critical sections to prevent multiple threads from accessing the critical section's code at the same time, thus only one active thread can update the data referenced by the code. Critical sections are useful for a non-nested mutex.

Unlike OpenMP atomic operations that provide fine-grain synchronization for a single operation, critical sections can provide course-grain synchronization for multiple operations.

Use:

  • #pragma omp critical with C/C++.

  • !$omp critical and !$omp end critical with Fortran.

If the optional (name) is omitted, it locks an unnamed global mutex. The easiest approach is to use the unnamed form unless this shared mutex is causing unacceptable performance delays.

TIP:
After you rewrite your code to use OpenMP* parallel framework, you can analyze its performance with Intel® Advisor perspectives. Use the Vectorization and Code Insights perspective to analyze how well you OpenMP code is vectorized or use the Offload Modeling perspective to model its performance on a GPU.

For example, consider this annotated C/C++ serial program:

  int count;
   void Tick() {
     ANNOTATE_LOCK_ACQUIRE(0);
        count++;
     ANNOTATE_LOCK_RELEASE(0);
  }
. . .

The parallel C/C++ code after adding #include <omp.h> and #pragma omp critical:

  #include <omp.h>  //prevents a load-time problem with a .dll not being found
  int count;
   void Tick() {
     // Replace Lock annotations
     #pragma omp critical
        count++;
  }
. . .

Consider this annotated Fortran serial code:

program ABC
   integer(kind=4) :: count = 0
 . . .
contains
subroutine Tick
  call annotate_lock_acquire(0)
    count = count + 1
  call annotate_lock_release(0)
end subroutine Tick
 . . .
end program ABC

The parallel Fortran code after adding use omp_lib, !$omp critical, and !$omp end critical:

program ABC
  use omp_lib
  integer(kind=4) :: count = 0
  . . .
  contains
   subroutine Tick
     !$omp critical
       count = count + 1
     !$omp end critical
   end subroutine Tick
 . . .
end program ABC