Lesson 12

Date: 4/16/2014
High Performance Computing (part I)
Linux for Engineering and IT applications


Synchronization Constructs

Exercise
  • 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];
        }
        printf("sum=%lf\n",sum);
    }
    
    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
    ./sum.x
    




  • Take me to the Course Website