OpenMP Directives: Synchronization Constructs


Consider a simple example where two threads on two different processors are both trying to increment a variable x at the same time (assume x is initially 0):


THREAD 1: THREAD 2:
High level code increment(x)
{
x = x + 1;
}
increment(x)
{
x = x + 1;
}
Assembly 10 LOAD A, (x address)
20 ADD A, 1
30 STORE A, (x address)
10 LOAD A, (x address)
20 ADD A, 1
30 STORE A, (x address)


One possible execution sequence:

  1. Thread 1 loads the value of x into register A.
  2. Thread 2 loads the value of x into register A.
  3. Thread 1 adds 1 to register A
  4. Thread 2 adds 1 to register A
  5. Thread 1 stores register A at location x
  6. Thread 2 stores register A at location x

The resultant value of x will be 1, not 2 as it should be.

To avoid a situation like this, the incrementing of x must be synchronized between the two threads to ensure that the correct result is produced.

OpenMP provides a variety of Synchronization Constructs that control how the execution of each thread proceeds relative to other team threads.