Intel® Advisor User Guide

ID 766448
Date 3/22/2024
Public

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

Document Table of Contents

Basic OpenMP Atomic Operations

Use OpenMP atomic operations to allow multiple threads to safely update a shared numeric variable, such as on hardware platforms that support atomic operation use. An atomic operation applies only to the single assignment statement that immediately follows it, so atomic operations are useful for code that requires fine-grain synchronization.

Before the statement to be protected, use:

  • #pragma omp atomic for C/C++.

  • !$omp atomic for Fortran.

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 code:

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

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

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

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 and the !$omp atomic directive:

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

The Intel Advisor Fortran sample nqueens.f90 demonstrates the use of an atomic operation.

This topic introduces basic OpenMP atomic operations. For advanced atomic operations that use clauses after the atomic construct, see Advanced OpenMP Atomic Operations.