13.11.2016 Views

OpenMP Application Programming Interface Examples

2fZ58Wr

2fZ58Wr

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Fortran<br />

1<br />

2<br />

3<br />

4<br />

5<br />

6<br />

7<br />

8<br />

The following example is non-conforming because the initialization (a = 0) of the original list<br />

item a is not synchronized with the update of a as a result of the reduction computation in the for<br />

loop. Therefore, the example may print an incorrect value for a.<br />

To avoid this problem, the initialization of the original list item a should complete before any<br />

update of a as a result of the reduction clause. This can be achieved by adding an explicit<br />

barrier after the assignment a = 0, or by enclosing the assignment a = 0 in a single directive<br />

(which has an implied barrier), or by initializing a before the start of the parallel region.<br />

Example reduction.6.c<br />

C / C++<br />

S-1 #include <br />

S-2<br />

S-3 int main (void)<br />

S-4 {<br />

S-5 int a, i;<br />

S-6<br />

S-7 #pragma omp parallel shared(a) private(i)<br />

S-8 {<br />

S-9 #pragma omp master<br />

S-10 a = 0;<br />

S-11<br />

S-12 // To avoid race conditions, add a barrier here.<br />

S-13<br />

S-14 #pragma omp for reduction(+:a)<br />

S-15 for (i = 0; i < 10; i++) {<br />

S-16 a += i;<br />

S-17 }<br />

S-18<br />

S-19 #pragma omp single<br />

S-20 printf ("Sum is %d\n", a);<br />

S-21 }<br />

S-22 return 0;<br />

S-23 }<br />

C / C++<br />

CHAPTER 7. DATA ENVIRONMENT 237

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!