Example Programmes for Parallel Systems
Now we shall complete this with the examples on shared memory programming.
Example 13: Adding elements of an array using two processor int sum, A[ n] ; //shared variables
void main ( ){
int i ;
for (i=0; i
// now create process to be implemented by processor P1
fork(1) add (A,n/2,n-1, sum); // process to add elements from index n/2 to -
1.sum is output variable // now create process to be implemented by processor
P0 add (A,0,n/2-1, sum);
join 1 ;
printf ("%d", sum);
}
add (int A[ ], int lower, int upper, int sum) {
int sum1=0, i;
for (i=lower; i<=upper; i++)
sum1=sum1+A[i];
lock sum;
sum=sum+sum1;
unlock sum ;
}
In this program, the last half of the array is passed to processor P1 which adds them. Meanwhile processor P0 adds the first half of the array. The variable sum is locked to avoid inconsistency.