multithreading - C++ matrix multiplication with multithreads and semaphore -
i have written program multiplication of 2 matrices. when execute it, works sometimes, not work , half of answers right. think there problem in usage of thread , semaphore together.
#include <iostream> #include <stdio.h> #include <stdlib.h> #include <mutex> #include <thread> //note: code needs c++11 compiler compile. using namespace std; int const size = 4; mutex mtx[size][size]; thread mythread[size]; void matrixmultiplication(int const * const * matrixa, int const * const * matrixb,int** matrixc, int row, int col, int i){ mtx[row][col].lock(); matrixc[row][col] += matrixa[row][i]*matrixb[i][col]; mtx[row][col].unlock(); } int main() { int** matrixa; int** matrixb; int** matrixc; matrixa = new int*[size]; matrixb = new int*[size]; matrixc = new int*[size]; for(int = 0; i<size; i++){ matrixa[i] = new int[size]; matrixb[i] = new int[size]; matrixc[i] = new int[size]; } //we initializing matrices. int count = 1; for(int = 0; i<size; i++){ for(int j = 0; j<size; j++){ matrixa[i][j] = count; matrixb[i][j] = count; count++; } } for(int row=0; row<size; row++){ for(int col=0; col<size;col++){ for(int i=0;i<size;i++){ mythread[i] = thread(matrixmultiplication, matrixa, matrixb, matrixc, row, col, i); mythread[i].join(); } } } for(int = 0; i<size; i++){ for(int j = 0; j<size; j++){ cout<<matrixc[i][j]<<" "; } cout<<endl; } return 0; }
there 2 things going wrong here far can see.
for(int row=0; row<size; row++){ for(int col=0; col<size;col++){ for(int i=0;i<size;i++){ mythread[i] = thread(matrixmultiplication, matrixa, matrixb, matrixc, row, col, i); mythread[i].join(); } } }
should be
for(int row=0; row<size; row++){ for(int col=0; col<size;col++){ for(int i=0;i<size;i++){ mythread[i] = thread(matrixmultiplication, matrixa, matrixb, matrixc, row, col, i); } } } for(int row=0; row<size; row++){ for(int col=0; col<size;col++){ for(int i=0;i<size;i++){ mythread[i].join(); } } }
this way first create bunch of calculations. , actual calculations. still not way should approach this. thread should have reasonable amount of work.
so before go ahead , that, allow me explain threading little bit. thread different work at same time. since doing @ same time, can never let thread access data might written thread. otherwise might end data that's half written to( called race condition).
therefore std::thread()
call copy arguments given. if it's pointer. can let each thread calculations each column on separate thread. however, in order recommend creating column
struct or class. , passing thread std::ref
. passing std::ref
prevent data being copied.
Comments
Post a Comment