Critical regions in OpenMP (OMP CRITICAL)


This exercise presents a simple program to demonstrate the use of OMP CRITICAL. In the code below, each thread increments c by its own rank. Thus the final value of c should be 0 + 1 + 2 + 3 +....+ number of threads. For example, if the number of threads is set to 4, the final value of c should be 6. Compile the code provided below. Set the number of threads to 4. Run the code several times. What do you observe? Is the result correct? How can you use OMP CRITICAL to ensure correct result?



int main(){
   int c=0, iam, i, num_threads;

#pragma omp parallel private(iam)
   iam = omp_get_thread_num();
   num_threads = omp_get_num_threads();

     for(i=1; i<1000; i++){
       if(i == 1) c += iam;
       else c = c;

#pragma omp barrier
#pragma omp for ordered schedule(dynamic)
     for(iam=0; iam