Hi!
So, I made this code
#include<iostream>
#include<cstdlib>
#include<pthread.h>
using namespace std;
const int m=6;
const int n=5;
const int s=5;
const int r=8;
const int num_thrd=3;
class data{
public:
int* A;
int* B;
int* C;
int start;
};
void* multiply(void* pod)
{
data* P=(data*)pod;
for(int i=P->start;i<m;i+=num_thrd)
{
for(int j=0;j<r;j++)
{
float sum=0;
for(int k=0;k<n;k++)
sum+=P->A[i*n+k]*P->B[k*r+j];
P->C[i*r+j]=sum;
}
}
}
int main()
{
int* A=new int[m*n];
int* B=new int[s*r];
for(int i=0;i<m*n;i++)
A[i]=rand()%10+1;
for(int i=0;i<s*r;i++)
B[i]=rand()%10+1;
if(n==s)
{
int* AB=new int[m*r];
pthread_t tID[num_thrd];
data* P=new data;
P->A=A;
P->B=B;
P->C=AB;
P->start=0;
for(int i=0;i<num_thrd;i++)
{
pthread_create(&tID[i],NULL,multiply,(void*)P);
P->start++;
}
for(int i=0;i<num_thrd;i++)
pthread_join(tID[i],NULL);
cout << "A [" << m << "*" << n << "]=" << endl;
for(int i=0;i<m*n;i++)
{
cout << A[i] << "\t";
if((i+1)%n==0) cout << endl;
}
cout << endl << "B [" << s << "*" << r << "]=" << endl;
for(int i=0;i<s*r;i++)
{
cout << B[i] << "\t";
if((i+1)%r==0) cout << endl;
}
cout << endl << "AB [" << m << "*" << r << "]=" << endl;
for(int i=0;i<m*r;i++)
{
cout << AB[i] << "\t";
if((i+1)%r==0) cout << endl;
}
delete[] AB;
}else
cout << "Matrices cant be multiplied!" << endl;
delete[] A;
delete[] B;
return 1;
}
It works fine, but the task was to make it using threads on both loops in thread function. First for-loop is for rows of matrix, and I made it using threads, but we should do it so that both rows and columns are calculated with threads. Do you have any idea on how to do it?
Thanks a lot