So I'm working on multipling 2 matrices in C++ using threads.
This is the code:
Code:
#include<iostream>#include<cstdlib>
#include<pthread.h>
using namespace std;
const int m=5;
const int n=4;
const int s=4;
const int r=6;
const int num_thrd_row=2;
const int num_thrd_col=3;
class data
{
public:
int* A;
int* B;
int* C;
int start;
int row;
int column;
data(int* a,int* b,int* c): A(a),B(b),C(c),start(0) {}
};
void* multiply_columns(void* dat)
{
data* P=(data*)dat;
int i=P->row;
for(int j=P->column;j<r;j+=num_thrd_col)//***problem***
{
float sum=0;
for(int k=0;k<s;k++)
sum+=P->A[i*n+k]*P->B[k*r+j];
P->C[i*r+j]=sum;
}
}
void* multiply_rows(void* dat)
{
data* P=(data*)dat;
pthread_t tID[m*num_thrd_col];
for(int i=P->start;i<m;i+=num_thrd_row)
{
P->row=i;
P->column=0;
for(int t=0;t<num_thrd_col;t++)
{
pthread_create(&tID[i*num_thrd_col+t],NULL,multiply_columns,(void*)P);
P->column++;//***problem***
}
for(int t=0;t<num_thrd_col;t++)
pthread_join(tID[i*num_thrd_col+t],NULL);
}
}
int main()
{
srand(time(NULL));
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* C=new int[m*r];
pthread_t tID[num_thrd_row];
data* P=new data(A,B,C);
for(int i=0;i<num_thrd_row;i++)
{
pthread_create(&tID[i],NULL,multiply_rows,(void*)P);
P->start++;
}
for(int i=0;i<num_thrd_row;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 << C[i] << "\t";
if((i+1)%r==0) cout << endl;
}
delete[] C;
}
else
cout << "Matrices cannot be multiplied!" << endl;
delete[] A;
delete[] B;
return 1;
}
Problem is, "j=P->column", because j is always equal to 3.
How can that be possible? In main thread is done the same thing (with P->start, and "i=P->start" works just fine. Thanks for your help.