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.

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.

For more complete information about compiler optimizations, see our Optimization Notice.