I am almost done writing a small applicaition that I was tasked with.
The application performs matrix multiplication with threads. The
application is almost complete, but I have a small bug in my app.
When I run the app I get most of the values calculated in the results
matrix, and the values are correct, but I always end up with 2, or 3
of the values being 0 in the matrix when it is displayed. None of the
values in the results matrix should have a zero value. Any idea what
is going on?
Code Block#include <string>
#include <iostream>
#include <windows.h>
#include <cstdio>
#include <cstdlib>
using namespace std;
//declare matrices as global variables
#define M 3
#define K 2
#define N 3
#define NUMBER_OF_THREADS 9
int A [M][K] = { {1,4}, {2,5}, {3,6}};
int B [K][N] = {{8,7,6}, {5,4,3}};
int C [M][N];
/* structure for passing data to threads */
struct v
{
int i; /*row*/
int j; /*column*/
};
DWORD WINAPI MatrixMult(LPVOID Param)
{
DWORD sum=0;
struct v *input = (struct v *) Param;
for(int l=0; l<2; l++)
{
sum=sum+((A[input->i][l])*(B[l][input->j]));
C[input->i][input->j]=sum;
}
return 0;
}
int main(){
DWORD waitValue;
DWORD ThreadIds[NUMBER_OF_THREADS];
HANDLE ThreadHandles[NUMBER_OF_THREADS];
int thread_index=0;
//we have to create M * N worker threads
for (int i=0; i<M; i++){
for (int j=0; j<N; j++)
{
struct v data;
data.i = i;
data.j = j;
/*Now create the thread passing it data as a parameter*/
ThreadHandles[thread_index]= CreateThread (
NULL, //default security attribtes
0, //default stack size
MatrixMult, //thread function
&data, //parameter to thread function
0, //default creation flags
&ThreadIds[thread_index]); //returns the thread identifier
if (!ThreadHandles)
{
cout<<"Error Creating Threads,,,,.exiting"<<endl;
return -1;
}
thread_index++;
}
}
//Must wait for multiple threads to complete
cout<<"\nWaiting for threads to complete....\n";
waitValue=WaitForMultipleObjects(9, ThreadHandles, TRUE, INFINITE);
if (waitValue == WAIT_FAILED)
{
cout<<"Wait value failed\n";
}
//display the computed results of the output
cout<<"The Results of the matrix multiplication are: \n";
for (int i=0; i<M; i++){
if(i>0)cout<<"\n";
for (int j=0; j<N; j++){
cout<<C[i][j]<<" ";
}
}
cout<<"\n";
// Close all thread handles upon completion.
for (int i=0; i<NUMBER_OF_THREADS; i++)
{
CloseHandle(ThreadHandles[i]);
}
return 0;
}