In OpenMP program, the function of atomic operations by #pragma omp atomic
providing guidance compiler directive. critical
Critical section operation capable of acting on a block of any size, and the atomic operation can only affect a single assignment statement , C \ C ++ available atomic operation is as follows:+ - * / & ^ | << >>
atomic in use need to pay attention to:
- When one atomic operation data, the data can not be protected critical section
- When the user operation for the same yard using a memory cell, it is necessary for all parts of the variable parallel assignment involves protection, were added in an atomic operation.
Example:
#include <stdio.h>
#include <omp.h>
int main()
{
omp_set_num_threads(2);
int counter = 0, i;
#pragma omp parallel
{
for (i = 0; i < 10000; i++)
{
#pragma omp atomic
counter++;
}
}
printf("counter = %d\n", counter);
return 0;
}
Due to the use of atomic statements, to avoid possible data access competition, the final results of the implementation are the same, the results are always counter = 20000
(assuming that there are two concurrent threads).