
Programming Using the
Message-Passing
Paradigm III
Dr. Cem Özdo
˘
gan
LOGIK
Parallelization
Application Example
Pi Computation
7.8
Pi Computation VI
1 i f ( n == 0) break ; /
*
Qui t when " 0 " entered
*
/
2 /
*
Computing l o c a l p i number f o r rank 0 process
*
/
3 /
*
I n t e g r a l l i m i t s are from 0 t o 1
*
/
4 h = (1.0 − 0.0) / ( double ) n ; /
*
Step l eng th
*
/
5 mysum = 0 . 0; /
*
I n i t i a l i z e sum va r iab l e
*
/
6 f o r ( i = rank +1; i <= n ; i += si ze ) /
*
Loop over i n t e r v a l f o r
i n t e g r a t i o n
*
/
7 {
8 x = h
*
( ( double ) i − 0 .5 ) ; /
*
Middle po i nt at step
*
/
9 mysum += 4.0 / ( 1. 0 + x
*
x ) ; /
*
Sum up a t each step
*
/
10 / / p r i n t f ( " i=%d x=%f sum=%f \ n " , i , x , sum) ; /
*
Int erm edi at e
steps
*
/
11 }
12 mypi = h
*
mysum; /
*
Obtain l o c a l r e s u l t i n g p i number
*
/
13 /
*
Receive a message c o nta i nin g lo c a l r e s u l t i n g pi number from
a l l oth er processes
*
/
14 f o r ( i =1; i < size ; i ++) {
15 MPI_Recv (& pi , 1 , MPI_DOUBLE, i , tag , MPI_COMM_WORLD, &s tat u s )
; /
*
Bl ockin g r eci ev e
*
/
16 p r i n t f ( " Process 0 : Received l o c a l r e s u l t i n g p i number : %.16 f
from process %d \ n " , pi , i ) ;
17 mypi=mypi+ p i ; /
*
Reduce a l l l o c a l values t o mypi v a ria b l e
*
/
18 }
19 p r i n t f ( " p i i s a ppr oxi matel y %.16 f , E rro r i s %.16 f \ n " , mypi , fabs (
mypi − PI25DT) ) ;
20 }
21 else /
*
Other processes do t h i s
*
/
22 {
23 MPI_Recv (&n , 1 , MPI_I NT , 0 , tag , MPI_COMM_WORLD, &s t at u s ) ; /
*
Bl ockin g rec ie ve
*
/