Tuesday, 24 March 2015

Write a concurrent program for Matrix Multiplication. Effective use of Multicore Architecture is expected.

//Program#include<iostream>
#include<pthread.h>
#include<cstdlib>

using namespace std;

#define size 3
int nthread;
int A[size][size],B[size][size],C[size][size];

void read(int m[size][size])
{
 int i,j,val;
 for(i=0;i<size;i++)
 for(j=0;j<size;j++)
 cin>>m[i][j];
}//read


void display(int m[size][size])
{
int i,j;
for(i=0;i<size;i++)
 {
  cout<<"\n";
  for(j=0;j<size;j++)
   cout<<m[i][j]<<" ";
 }
} //display


void* multiply(void* tcnt)
{
 int a=(int)tcnt;   
 int from=(a*size)/nthread;
 int to=((a+1)*size)/nthread;
 int i,j,k;

 //multiplication on individual thread
 cout<<"\n Thread Execution :"<<a<<"...[->from row "<<from<<"to "<<to-1<<"]"<<endl;
 for(i=from;i<to;i++)
 {
  for(j=0;j<size;j++)
   {
    C[i][j]=0;
    for(k=0;k<size;k++)
     C[i][j]+=A[i][k]*B[k][j];
   }
  }
 cout<<"\n Execution of thread "<<a<<"is finished. "<<endl;

}//multiply function




int main(int argc,char* argv[])
{
 int i;
 if(argc!=2)
 {
  cout<<"\n Usage :"<<argv[0]<<"number of threads \n ";
  exit(-1);
  }
 //read command line argument for thread count
 nthread=atoi(argv[1]);
 pthread_t thread[nthread];//create thread array of nthread size

 cout<<"\n Enter values of matrix A : \n";
 read(A);
 cout<<"\n Enter values of matrix B : \n";
 read(B);

 for(i=0;i<nthread;i++)
  {
   //create thread and use each thread for multiplication
   pthread_create(&thread[i],NULL,multiply,(void *)i);
    sleep(1);
  }

 //main thread works on thread 0 as it is first thread if main thread =1 then it does everything

 multiply(0);
 for(i=1;i<nthread;i++)
 pthread_join(thread[i],NULL);//main thread waits until other threads complete

 cout<<"\n \nMatrix A: \n";
 display(A);
 cout<<"\n \nMatrix B: \n";
 display(B);
 cout<<"\n \nMatrix C: \n";
 display(C);

 cout<<"\n \n ";
  return 0;
 }//main



/* Expected Output :
svcet@svcet-HoD:~/Desktop$ g++ multi.cpp -o multi -fpermissive -lpthread
svcet@svcet-HoD:~/Desktop$ ./multi 3

 Enter values of matrix A :
1 2 3
1 2 3
1 2 3

 Enter values of matrix B :
1 2 3
1 2 3
1 2 3

 Thread Execution :0...[->from row 0to 0]

 Execution of thread 0is finished.

 Thread Execution :1...[->from row 1to 1]

 Execution of thread 1is finished.

 Thread Execution :2...[->from row 2to 2]

 Execution of thread 2is finished.

 Thread Execution :0...[->from row 0to 0]

 Execution of thread 0is finished.


Matrix A:

1 2 3
1 2 3
1 2 3

Matrix B:

1 2 3
1 2 3
1 2 3

Matrix C:

6 12 18
6 12 18
6 12 18

*/

No comments:

Post a Comment