You are here
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?
integer omp_get_thread_num,omp_get_num_threads,c,iam c=0 !$OMP PARALLEL PRIVATE(iam) iam=omp_get_thread_num() do i = 1,1000 if(i .eq. 1) then c = c + iam else c=c endif enddo !$OMP BARRIER !$OMP DO ORDERED SCHEDULE(dynamic) do iam = 0, omp_get_num_threads()-1 !$OMP ORDERED print *, iam, c !$OMP END ORDERED enddo !$OMP END DO !$OMP END PARALLEL end