Skip to content

Instantly share code, notes, and snippets.

@abrarShariar
Created July 11, 2018 23:25
Show Gist options
  • Save abrarShariar/da1e8f500f514545655c2950c4d034ec to your computer and use it in GitHub Desktop.
Save abrarShariar/da1e8f500f514545655c2950c4d034ec to your computer and use it in GitHub Desktop.
Matrix multiplication with threads
#include<iostream>
#include<thread>
#include<fstream>
using namespace std;
/*input
4 //number of matrix
2 2 //dimension
1 2
4 5
3 2
6 5
1 1
2 2
4 4
5 6
*/
class Matrix {
private:
int grid[100][100];
public:
void setValue(int r, int c, int value){
this->grid[r][c] = value;
}
int getValue(int r, int c) {
return this->grid[r][c];
}
};
Matrix multiplyMatrix(Matrix m1, Matrix m2, int row, int col){
Matrix result;
for(int i=0;i<row;i++){
for(int j=0;j<col;j++){
int res = 0;
for(int k=0;k<col;k++){
res += m1.getValue(i,k) * m2.getValue(k,j);
}
result.setValue(i,j,res);
}
}
return result;
}
void scanMat(Matrix m1, Matrix m2, int row, int col, int index){
cout<<endl;
cout<<"Thread index: "<<index<<endl;
cout<<"Result (after multiplication): "<<endl;
Matrix result = multiplyMatrix(m1, m2, row, col);
for(int i=0;i<row;i++){
for(int j=0;j<col;j++){
cout<<result.getValue(i,j)<<" ";
}
cout<<endl;
}
cout<<endl;
}
int main(){
int tests, row, col;
ifstream cin("input_3.txt");
cin>>tests>>row>>col;
int val;
Matrix matArr[tests];
for(int i = 0;i < tests;i++) {
for(int j=0;j<row;j++) {
for(int k=0;k<col;k++){
cin>>val;
matArr[i].setValue(j,k,val);
}
}
}
//test print all matrix
/*
for(int i = 0;i < tests;i++){
for(int j=0;j<row;j++){
for(int k=0;k<col;k++){
cout<<matArr[i].getValue(j,k)<<" ";
}
cout<<endl;
}
}
*/
thread thArr[tests/2];
int tCount = 0;
for(int i=0;i<tests;i+=2){
thArr[tCount] = thread(scanMat, matArr[i], matArr[i+1], row, col, tCount);
tCount++;
}
//join with main thread
for(int i=0;i<tCount;i++){
thArr[i].join();
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment