I have just started with O.S programming and was exploring threads. I want to multiply 2 matrices and get their product using the pthread_create(), pthread_join() and pthread_exit() functions. However, pthread_create() takes input as void* whereas, I want to pass an int** parameter.
I already tried:
- Passing m3 [my resultant matrix] in the pthread_create() function by typecasting it as (void*) and then typecasting it back to (int**) in my threadMultiply function but that didnt work
- Putting m1,m2,m3 as global variables but that too gave me errors.
I am very confused and don't know how to approach this anymore. Any help would be much appreciated, thanks
#include <stdio.h>
#include <pthread.h>
#include <stdlib.h>
#include <unistd.h>
int** alloc(int, int);
void display(int**, int, int);
void* threadMultiply(void* para);
int main()
{
int r1,c1,r2,c2,r3,c3; // rows and columns of each matrix
int **m1, **m2, **m3; // all 3 matrices
// took inputs for r1,c1,r2,c2
m1=alloc(r1,c1);
printf("Enter the %d elements of the first matrix\n", r1*c1);
for(int i=0;i<r1;i++)
for(int j=0;j<c1;j++)
scanf("%d", &m1[i][j]);
m2=alloc(r2,c2);
printf("Enter the %d elements of the second matrix\n", r2*c2);
for(int i=0;i<r2;i++)
for(int j=0;j<c2;j++)
scanf("%d", &m2[i][j]);
display(m1, r1, c1);
display(m2, r2, c2);
if(c1 != r2)
{
printf("\nMatrices cannot be multiplied, check dimensions");
return 0;
}
r3 = r1;
c3 = c2;
m3=alloc(r3,c3);
int MAX_THREADS = r3*c3;
pthread_t threads[MAX_THREADS];
// Creating threads.
for (int i = 0; i < MAX_THREADS; i++)
{
int *p;
pthread_create(&threads[i], NULL, threadMultiply, (void*)(p)); //variable 'i' is of type int however function takes parameter of type void* so we have to do type-casting
}
// joining and waiting for all threads to complete
for (int i = 0; i < MAX_THREADS; i++)
pthread_join(threads[i], NULL);
printf("\nThe resultant matrix is:");
display(m3, r3, c3);
return 0;
}
int** alloc(int row, int col)
{
//dynamic memory allocation for first 2 matrices
int **m=0;
m=(int**)malloc(row*sizeof(int*));
for(int i=0;i<row;i++)
{
*(m+i)=(int*)malloc(col*sizeof(int));
}
return m;
}
void *threadMultiply(void *para)
{
int i,j,k;
for(i=0;i<r1;i++)
{
for(j=0;j<c2;j++)
{
m3[i][j] == 0
for(k=0;k<c1;k++)
m3[i][j]+=m1[i][k] * m2[k][j];
}
}
printf("thread finished ...");
pthread_exit(NULL);
}
p. You don't need to cast to avoid *. You do need to castparatoint **within your thread function. - Cheatahm1,m2, andm3but they're not defined in that context so this shouldn't compile. You're also not using the function's parameter or passing it anything meaningful. Please show one of your actual attempts with input, expected output, and actual output. - dbush