Program 2Matrix Multiplication 1 Wrtie a PThreads program to
Program 2-Matrix Multiplication
1) Wrtie a PThreads program to calculate matrix multiplication
a) You can start with the code from the examples page
b) It should work with a varialble number of threads reguardless of matrix size
c) From the command line It should accept the number of threads to use
1) For quick debugging purposes use a default number of threads
2) Compare to serial version
a) Log into Cheetah, then SSH into amdquad01
b) Run the serial program for matirces of size NxN, Where N=1024
c) Run the parellel program for matrices of same size N
1)Time for the following number of threads: 1,2,3,4, 8, 16, 32
3) Deliverables
a) Source Code
b) Graph of Results
Solution
Source Code in Pthreads for matrix multiplication
#include<pthread.h>
#include<stdio.h>
#include<stdlib.h>
#define A 3
#define B 2
#define C 3
#define NUM_T 10 //number of threads
int x[A][B]={{1,2},{1,2},{3,2}};
int y[B][C]={{1,2,3},{4,5,6}};
int z[A][C];
struct s{
int m; //row
int n;//column
};
void * thread1(void *p); // the thread
int main(int argc, char *argv[])
{
int i,j,count=0;
for(i=0;i<A;i++){
for(j=0;j<C;j++){
//Assig a row and column for each thread
struct s* data=(struct s*)malloc(sizeof(struct s));
data ->m=i;
data ->n=j;
//Now create the thread
pthread_t tid; //thread Id
pthread_attr_t attr;// set of thread attributes
//default attributes
pthread_attr_init(&attr);
//finally create the thread
pthread_create(&tid,&attr,runner,data);
//use join method so that parent wait untill all threads complete
pthread_join(tid,NULL);
count++;
}
}
//resulting matrix
for(i=0;i<A;i++){
for(j=0;j<C;j++){
printf(\"\ %d\",z[i][j]);
}
}
//thread will begin control in this function
void * thread1(void *p)
{
struct s* data=p;//structure that holds data
int n1,sum1=0;//the counter and sum;
//row*column loop
for(n1=0;n1<B;n1++)
{
sum1+=A[data->m][n1]*B[n1][data->n];
}
//assign the sum in result
z[data->m][data->n]=sum1;
pthread_exit(0);
}
Pthread is POSIX thread is a parallel execution model. As given in condition that the program should work with variable number of threads regardless of matrix size


