Oracle® Solaris Studio 12.4: OpenMP API User's Guide

Exit Print View

Updated: December 2014
 
 

4.7.2 OpenMP Locks

Since OpenMP 3.0, locks are owned by tasks, not by threads. Once a lock is acquired by a task, the task owns it, and the same task must release it before the task is completed. However, the critical construct remains a thread-based mutual exclusion mechanism.

Because locks are owned by tasks, take extra care when using locks. The following example conforms to the OpenMP 2.5 specification because the thread that releases the lock lck in the parallel region is the same thread that acquired the lock in the sequential part of the program. The master thread of the parallel region and the initial thread are the same. However, the example does not conform to later specifications because the task region that releases the lock lck is different from the task region that acquired the lock.

Example 4-7  Using Locks Prior to OpenMP 3.0
#include <stdlib.h>
#include <stdio.h>
#include <omp.h>

int main()
{
  int x;
  omp_lock_t lck;

  omp_init_lock (&lck);
  omp_set_lock (&lck);
  x = 0;

  #pragma omp parallel shared (x)
  {
    #pragma omp master
    {
      x = x + 1;
      omp_unset_lock (&lck);
    }
  }
  omp_destroy_lock (&lck);
}