I'm creating a matrix class in C++ made of 2-dimensional vectors and I'm trying to use multithreading for the multiplication operation. Here are the two functions in question:
// Global variables for threading
std::vector<std::vector<double>> multiSecond;
std::vector<std::vector<double>> multiResult;
std::vector<std::vector<double>> multiFirst;
int step_i = 0;
void* multi(void*){
int core = step_i++;
for(int i = core; i < core + 1; i++){
for(int j = 0; j < multiSecond[0].size(); j++){
for(int k = 0; k < multiFirst[0].size(); k++){
multiResult[i][j] += multiFirst[i][k] * multiSecond[k][j];
}
}
}
}
class Matrix{
private:
int rows;
int columns;
public:
std::vector<std::vector<double>> matrix;
...
Matrix operator * (const Matrix &obj){
multiResult = std::vector<std::vector<double>>
(rows, std::vector<double>(obj.columns));
multiSecond = obj.matrix;
multiFirst = matrix;
step_i = 0;
pthread_t threads[rows];
for(int i = 0; i < rows; i++) {
int* p;
pthread_create(&threads[i], NULL, multi, (void*)(p));
}
for(int i = 0; i < rows; i++){
pthread_join(threads[i], NULL);
}
Matrix product(multiResult);
return product;
}
...
In a test file I'm multiplying to matricies:
std::vector<std::vector<double>> u {{1, 2, 3}, {3, 2, 1}, {2, 1, 3}, {3, 1, 2}};
std::vector<std::vector<double>> w {{1, 2, 3}, {2, 4, 1}, {1, 3, 2}};
Matrix U(u);
Matrix W(w);
Matrix X = U * W;
X.print(3);
These are some of the results from running this multiplication:
(correct answer)
8.000 19.000 11.000
8.000 17.000 13.000
7.000 17.000 13.000
7.000 16.000 14.000
15.000 27.000 19.000
8.000 17.000 13.000
7.000 17.000 13.000
0.000 0.000 0.000
8.000 36.000 22.000
8.000 17.000 13.000
7.000 17.000 13.000
0.000 0.000 0.000
11.000 38.000 22.000
8.000 17.000 13.000
7.000 17.000 13.000
0.000 0.000 0.000
It gives the correct answer about 90% of the time.