// Guide to Java, Second Edition
// Copyright 2023, by J.T. Streib and T. Soma
public class InnerProductParallel {
public static void main(String[] args) {
int numThreads, vecSize;
int innerProduct;
innerProduct = 0;
numThreads = Integer.parseInt(args[0]);
vecSize = Integer.parseInt(args[1]);
int[] a, b;
a = new int[vecSize];
b = new int[vecSize];
getVec(a);
getVec(b);
// parallel section
//#omp parallel num_threads(numThreads)
shared(numThreads, innerProduct, vecSize, a, b)
{
int myPart, myID, myFirstPos, myLastPos;
int myInnerProduct;
myInnerProduct = 0;
myPart = vecSize / numThreads;
myID = Pyjama.omp_get_thread_num();
myFirstPos = myPart * myID;
if(myID == numThreads-1)
myLastPos = vecSize;
else
myLastPos = myFirstPos + myPart;
// multiplication and addition
for(int i=myFirstPos; i<myLastPos; i++)
myInnerProduct = myInnerProduct + (a[i] * b[i]);
// critical section: update innerProduct
//#omp critical
{
innerProduct += myInnerProduct;
} // end of critical section
} // end of parallel section
// print the contents of vectors if the size is small
if(vecSize <= 10) {
System.out.print("a = [");
for(int i=0; i<vecSize; i++)
System.out.print(a[i] + " ");
System.out.println("]");
System.out.print("b = [");
for(int i=0; i<vecSize; i++)
System.out.print(b[i] + " ");
System.out.println("]");
}
System.out.println("Inner Product is " + innerProduct);
}
public static void getVec(int[] array) {
for(int i=0; i<array.length; i++)
array[i] = (int)(Math.floor(Math.random() * 1000));
}
}