I am looking to make a matrix multiply by threads, where each thread performs one multiplication, and then the main thread will add all the results and put them in the appropriate place in the final matrix (after the other threads came out).
The way I'm trying to do this is to create an array of strings containing the results of each thread. Then I will go through the array and add + put the results in the resulting matrix.
Example: if you have matrices:
A = [{1,4}, {2,5}, {3,6}] B = [{8,7,6}, {5,4,3}]
Then I need an array containing [8, 20, 7, 16, 6, 12, 16, etc.]. Then I go through the array, adding up every 2 numbers and putting them in my last array.
This is the purpose of HW, so I am not looking for the exact code, but some logic on how to properly store the results in an array. I'm struggling to keep track of where I am in each matrix so as not to miss any numbers.
Thank.
EDIT2: Remember that there must be one thread for each individual multiplication. The value for the above example will consist of 18 threads, each of which performs its own calculation.
EDIT: I use this code as the basis for work.
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#define M 3
#define K 2
#define N 3
#define NUM_THREADS 10
int A [M][K] = { {1,4}, {2,5}, {3,6} };
int B [K][N] = { {8,7,6}, {5,4,3} };
int C [M][N];
struct v {
int i;
int j;
};
void *runner(void *param);
int main(int argc, char *argv[]) {
int i,j, count = 0;
for(i = 0; i < M; i++) {
for(j = 0; j < N; j++) {
struct v *data = (struct v *) malloc(sizeof(struct v));
data->i = i;
data->j = j;
pthread_t tid;
pthread_attr_t attr;
pthread_attr_init(&attr);
pthread_create(&tid,&attr,runner,data);
pthread_join(tid, NULL);
count++;
}
}
for(i = 0; i < M; i++) {
for(j = 0; j < N; j++) {
printf("%d ", C[i][j]);
}
printf("\n");
}
}
void *runner(void *param) {
struct v *data = param;
int n, sum = 0;
for(n = 0; n< K; n++){
sum += A[data->i][n] * B[n][data->j];
}
C[data->i][data->j] = sum;
pthread_exit(0);
}
Source: http://macboypro.wordpress.com/2009/05/20/matrix-multiplication-in-c-using-pthreads-on-linux/