Hi,
This code has been written to multiply 2 matrices using threads. The computation of each element of the matrix happens in the thread. As you can see at the end of the code, the sample outputs are not only wrong but different for 2 separate runs. I am not sure where the code is wrong. I am guessing it is the way the CPU schedules the threads.
Any help would be appreciated.
Thanks
V
Code:
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
//GLOBAL CONSTANTS
#define M 3
#define K 2
#define N 3 //Matrix sizes
int A [M][K] = { {1,4}, {2,5}, {3,6} }; //global matrices
int B [K][N] = { {8,7,6}, {5,4,3} };
//GLOBAL VARIABLES
int C [M][N]; //resultant matrix
void *calc_Cell(void * num1); //calculates each cell of matrix
int main(int argc, char *argv[]) //
{
pthread_t tid[M][N];//declare pthread id matrix
//pthread_attr_t attr;
int cellPosition[2];//declare position array to pass to threads
//pthread_attr_init(&attr);
int i,j; //placeholders for double-loop to traverse matrix
//printf("Part 1\n");
for(i = 0; i < M; i++)
for(j = 0; j < N; j++)
{
cellPosition[0] = i;//assign i and j locations to array to pass to thread
cellPosition[1] = j;
//printf("Inside first loop:\n");
pthread_create(&tid[i][j], NULL, *calc_Cell, (void *) cellPosition);//create a new thread to calculate sum of cell [i][j]
}
//printf("Part 2\n");
for(i = 0; i < M; i++)
for(j = 0; j < N; j++)
pthread_join(tid[i][j], NULL);//wait until each cell is finished calculating
//printf("Part 3\n");
for(i = 0; i < M; i++)
{ printf("\n");
for(j = 0; j < N; j++)
{ printf("%d\t", C[i][j]);//print resultant matrix
}//line 40
}
return 0;
}
void *calc_Cell(void * num1){
//int cell = 0;
//printf("%d", atoi(num1), "\n");
int *line; //int pointer to receive void pass
line = (int *) num1; //assign void array to int array
int z;
for(z = 0; z < K; z++)
C[line[0]][line[1]] += (A[line[0]][z] * B[z][line[1]]);//calculate cell line[0]line[1] of matrix C
//printf("%d\t", C[line[0]][line[1]]);
pthread_exit(0);
//C[line[0]][line[1]] = cell;
}
/*SAMPLE RUN #1
0 0 0
0 0 0
0 45 288
SAMPLE RUN #2
0 0 0
0 0 0
0 0 324
*/