Lesson 13

Date: 4/19/2017
High Performance Computing (part I: OpenMP)
Linux System Administration

Synchronization Constructs

  • The CRITICAL directive specifies a region of code that must be executed by only one thread at a time. All threads in the team will attempt to execute in parallel, however, because of the CRITICAL construct surrounding the increment of sum, only one thread will be able to read/increment/write sum at any time.
    C / C++ - critical Directive Example
    #include <omp.h>
    #include <stdio.h>
    int main() {
        double a[1000000];
        int i;
        #pragma omp parallel for 
        for (i=0; i<1000000; i++) a[i]=i;
        double sum = 0;
        #pragma omp parallel for shared (sum) private (i) 
        for ( i=0; i < 1000000; i++) {
           #pragma omp critical   
            sum = sum + a[i];
    Copy the content of the code above into file sum.c, then compile and run it as follows:
    gcc -fopenmp -o sum.x sum.c
    export OMP_NUM_THREADS=4

  • Take me to the Course Website