/********************************************* In this example we have NUM_THREADS threads that share N values. Each one taking a chunk of size CHUNKSIZE every time. C is a shared Value between all the threads gcc -fopenmp -Wall -Werror example3OMP.c -o a.out bash-4.1$ ./a.out Thread 0: counter = 200 Thread 3: counter = 200 Thread 2: counter = 200 Thread 1: counter = 200 Thread 5: counter = 100 Thread 4: counter = 100 Average Value is 999.000000 ************************************************/ #include #include #define CHUNKSIZE 100 #define N 1000 #define NUM_THREADS 10 int main () { int i, chunk, counter=0; float a[N], b[N], c; /* Some initializations */ for (i=0; i < N; i++) a[i] = b[i] = i * 1.0; chunk = CHUNKSIZE; omp_set_num_threads(NUM_THREADS); int execute = 1; #pragma omp parallel num_threads(20) shared(a,b,c,chunk) private(i,counter) if(execute) { counter=0; #pragma omp for schedule(static, chunk) for (i=0; i < N; i++){ /* A critical section so ONLY ONE thread can update c */ /* #pragma omp critical [ ( name ) ] s t r u c t u r e d block Provides a region of mutual exclusion where only one thread can be working at any given time. By default all critical regions are the same, but you can provide them with names. Only those with the same name synchronize i.e. #pragma omp critical ( x ) */ #pragma omp critical { c += a[i] + b[i]; } counter++; } printf("Thread %d: counter = %d\n",omp_get_thread_num (),counter); } /* End of parallel section. All Thread join master thread and terminate */ /* Implicit barrier at the end of the parallel region */ printf("Average Value is %f\n",c/N); return 0; } /***************************************************************************** MORE ON SYNCHRONIZATION #pragma omp atomic x++; #pragma omp atomic expression Provides an special mechanism of mutual exclusion to do read & update operations Only supports simple read & update expressions E.g., x += 1, x = x - foo() Only protects the read & update part foo() not protected Usually much more efficient than a critical construct Not compatible with critical #pragma omp barrier Threads cannot proceed past a barrier point until all threads reach the barrier AND all previously generated work is completed Some constructs have an implicit barrier at the end E.g., the parallel construct */