OpenMP atomic atomic operation

In OpenMP program, the function of atomic operations by #pragma omp atomicproviding guidance compiler directive. criticalCritical 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:

  1. When one atomic operation data, the data can not be protected critical section
  2. 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).

Published 673 original articles · won praise 644 · views 380 000 +

Guess you like

Origin blog.csdn.net/zhaohaibo_/article/details/90408969