title: C++ matrix multiplication with multithreads and semaphore
body: <p>I have written a program that does a multiplication of two matrices. When I execute it, it works sometimes, sometimes it does not work and sometimes half of the answers are right. I think there is a problem in the usage of thread and semaphore together.</p>
  
  <pre><code>#include &lt;iostream&gt;
  #include &lt;stdio.h&gt;
  #include &lt;stdlib.h&gt;
  #include &lt;mutex&gt;
  #include &lt;thread&gt;
  
  //NOTE: THIS CODE NEEDS C++11 COMPILER TO 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 i = 0; i&lt;size; i++){
          matrixA[i] = new int[size];
          matrixB[i] = new int[size];
          matrixC[i] = new int[size];
      }
  
      //WE ARE INITIALIZING MATRICES.
      int count = 1;
      for(int i = 0; i&lt;size; i++){
          for(int j = 0; j&lt;size; j++){
              matrixA[i][j] = count;
              matrixB[i][j] = count;
              count++;
          }
      }
  
  
      for(int row=0; row&lt;size; row++){
          for(int col=0; col&lt;size;col++){
              for(int i=0;i&lt;size;i++){
                  myThread[i] = thread(MatrixMultiplication, matrixA, matrixB, matrixC, row, col, i);
                  myThread[i].join();
              }
          }
      }
  
  
      for(int i = 0; i&lt;size; i++){
          for(int j = 0; j&lt;size; j++){
              cout&lt;&lt;matrixC[i][j]&lt;&lt;"  ";
          }
          cout&lt;&lt;endl;
      }
  
      return 0;
  }
  </code></pre>