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