1.11M Members

C++ Matrix Multiplication with Threads

 
0
 

I need to multiply 2 matrices together using threads to computer each element. Ive been working on it myself but Im stuck at this point and Im getting an error. Here is the code I have.
Can someone help in explaining what is wrong here or how to correct it? I would really like to understand this and not just get the answer also. Thank you

When compiling this is what I get:
matrix_multi_threads.cc: In function âvoid* matrixMult(void*)â:
matrix_multi_threads.cc:62: error: âvoid*â is not a pointer-to-object type
matrix_multi_threads.cc:63: error: âvoid*â is not a pointer-to-object type

Any help would be appreciated so that I can get this working!

#include <stdio.h>
#include <pthread.h>
#include <stdlib.h>
#include <iostream>
 
using namespace std;
 
#define M 3      // Matrix sizes
#define K 2
#define N 3
 
int A[M][K] = { {1,4}, {2,5}, {3,6} };   // Matrices
int B[K][N] = { {8,7,6}, {5,4,3} };
int C[M][N];
 
struct v
{
   int i;       // row
   int j;       // column
};
 
void *matrixMult(void * data);
 
int main()
{
        pthread_t threadID[M][N];
        pthread_attr_t attr;
        pthread_attr_init(&attr);
 
/* Create M * N threads */
for(int i = 0; i < M; i++)
{
   for(int j = 0; j < N; j++)
   {
        struct v *data = (struct v *) malloc(sizeof(struct v));
        data->i = i;
        data->j = j;
 
        pthread_create(&threadID[i][j], NULL, *matrixMult, (void
        *) data);
    }
}
 
/* Joining the threads*/
for( int i = 0; i < M; i++ )
{
   for(int j = 0; j < N; i++ )
   {
        pthread_join(threadID[i][j],NULL);
   }
}
 
return 0;
}
 
void *matrixMult(void *data)
{
   int a = data-> i;
   int b = data-> j;
 
   C[a][b] = ( A[a][0] * B[0][b] ) + ( A[a][1] * B[1][b] );
 
   pthread_exit(0);
}
 
0
 

IMHO the errors are from the fact that you haven't typecasted *data at the beginning of the function to struct v * ....
so try it this way:

void * matrixMult(void *data)
{
   struct v * data2 = (struct v*)data;
   int a = data2->i;
   int b = data2->j;
}
 
0
 

I would think that sometime after the statement:
struct v *data = (struct v *) malloc(sizeof(struct v));
that free(data) should be utilized. Am I incorrect?

You
This article has been dead for over six months: Start a new discussion instead
Post:
Start New Discussion
Tags Related to this Article