We will rewrite the dot product example using a function to compute the dot product of the shared arrays given with the two different data distributions.
<function3.c>=
#include <stdio.h>
#include <upc.h>
#define NperTHREAD 10
#define SIZE (NperTHREAD * THREADS)
#define BLOCK NperTHREAD
shared float dot_cyc, dot_blk;
shared float x_cyc[SIZE], y_cyc[SIZE];
shared [BLOCK] float x_blk[SIZE], y_blk[SIZE];
shared float partialdot[THREADS];
main ()
{
int i;
float *myx, *myy;
float dot_product();
if( MYTHREAD == 0 ) {
for( i=0; i< SIZE; i++ ){
x_cyc[i] = (float) i;
y_cyc[i] = x_cyc[i];
x_blk[i] = (float) i;
y_blk[i] = x_blk[i];
}
}
upc_barrier(1);
myx = (float *) &x_cyc[MYTHREAD] ;
myy = (float *) &y_cyc[MYTHREAD] ;
printf("The dot product for cyclic dist in thread %2d is %g\n", MYTHREAD,
dot_product( myx, myy, NperTHREAD) );
upc_barrier(2);
myx = (float *) &x_blk[MYTHREAD*NperTHREAD] ;
myy = (float *) &y_blk[MYTHREAD*NperTHREAD] ;
printf("The dot product for block dist in thread %2d is %g\n", MYTHREAD,
dot_product( myx, myy, NperTHREAD) );
return(0);
}
float dot_product( float *x, float *y, int k)
{
int i, t;
float dotprod = 0.0;
float mydotprod = 0.0;
for( i=0; i<k; i++ ) {
mydotprod += x[i] * y[i];
}
partialdot[MYTHREAD] = mydotprod;
printf ("Thread %2d holds %g partial sum\n", MYTHREAD, partialdot[MYTHREAD]);
upc_barrier(10);
for( t=0; t < THREADS ; t++) {
dotprod += partialdot[t];
}
return( dotprod );
}