Intel® Advisor User Guide

ID 766448
Date 7/13/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 Locks

Consider the following annotated C/C++ serial code:

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

To implement a lock, use the OpenMP types, variables, and functions to provide more flexible and powerful use of locks. For example, for simple locks, use the omp_lock_t type in C/C++ or the type=omp_lock_kind in Fortran.

Locks can be wrapped inside C++ classes, as shown in the following parallel C/C++ code:

#include <omp.h>
  int count;
  omp_lock_t countMutex;
 
struct CountMutexInit {
     CountMutexInit() { omp_init_nest_lock   (&countMutex);   }
    ~CountMutexInit() { omp_destroy_nest_lock(&countMutex); }
} countMutexInit;     

// The declaration of the above object causes countMutex to
// be initialized on program startup, and to be destroyed when
// the program completes, via the constructor and destructor.


struct CountMutexHold {
     CountMutexHold() { omp_set_nest_lock    (&countMutex); }
    ~CountMutexHold() { omp_unset_nest_lock  (&countMutex); }
};

void Tick() {
    // unlocks on scope exit
    CountMutexHold releaseAtEndOfScope;
      count++; 
    }