testsuite/libgomp.c/appendix-a/a.18.1.c

Go to the documentation of this file.
00001 /* { dg-do run } */
00002 
00003 #include <omp.h>
00004 #include <stdio.h>
00005 
00006 extern void abort (void);
00007 
00008 #define NUMBER_OF_THREADS 4
00009 
00010 int synch[NUMBER_OF_THREADS];
00011 int work[NUMBER_OF_THREADS];
00012 int result[NUMBER_OF_THREADS];
00013 int
00014 fn1 (int i)
00015 {
00016   return i * 2;
00017 }
00018 
00019 int
00020 fn2 (int a, int b)
00021 {
00022   return a + b;
00023 }
00024 
00025 int
00026 main ()
00027 {
00028   int i, iam, neighbor;
00029   omp_set_num_threads (NUMBER_OF_THREADS);
00030 #pragma omp parallel private(iam,neighbor) shared(work,synch)
00031   {
00032     iam = omp_get_thread_num ();
00033     synch[iam] = 0;
00034 #pragma omp barrier
00035     /*Do computation into my portion of work array */
00036     work[iam] = fn1 (iam);
00037     /* Announce that I am done with my work. The first flush
00038      * ensures that my work is made visible before synch.
00039      * The second flush ensures that synch is made visible.
00040      */
00041 #pragma omp flush(work,synch)
00042     synch[iam] = 1;
00043 #pragma omp flush(synch)
00044     /* Wait for neighbor. The first flush ensures that synch is read
00045      * from memory, rather than from the temporary view of memory.
00046      * The second flush ensures that work is read from memory, and
00047      * is done so after the while loop exits.
00048      */
00049     neighbor = (iam > 0 ? iam : omp_get_num_threads ()) - 1;
00050     while (synch[neighbor] == 0)
00051       {
00052 #pragma omp flush(synch)
00053       }
00054 #pragma omp flush(work,synch)
00055     /* Read neighbor's values of work array */
00056     result[iam] = fn2 (work[neighbor], work[iam]);
00057   }
00058   /* output result here */
00059   for (i = 0; i < NUMBER_OF_THREADS; i++)
00060     {
00061       neighbor = (i > 0 ? i : NUMBER_OF_THREADS) - 1;
00062       if (result[i] != i * 2 + neighbor * 2)
00063     abort ();
00064     }
00065 
00066   return 0;
00067 }

Generated on Fri Apr 5 05:38:10 2013 for Libgomp by  doxygen 1.4.7