multiplying 2 2D arrays using fork()
-
13-12-2019 - |
Question
i am trying to multiply a[2][3] with b[3][4] and put the answer in c[2][4]. I have to use fork() and make 2 processes, each child for c[0][j] and c[1][j], parent will wait. So each child process will calculate a row for c. This is my code :
//multiply a[2][3] * b[3][4] = c[2][4]
//with fork
//each child completes one c[2][4]'s row
#include<stdio.h>
#include<stdlib.h>
main()
{
int a[2][3]={1,2,3,
4,5,6};
int b[3][4]={1,2,3,4,
5,6,7,8,
9,10,11,12};
int c[2][4];
int i,j;
int m; //for the calculation
int n; //common 3
int pid; //fork
for(i=0;i<2;i++)
{
pid=fork();
if(pid==-1)
{
printf("Can't fork\n");
}
if(pid==0)//child
{
for(j=0;j<4;j++)
{
for(n=0;n<3;n++)
{
m=m+a[i][n]*b[n][j];
}
c[i][j]=m;
m=0;
}
exit(EXIT_SUCCESS);
}
if(pid>0)//parent
{
wait(0);
}
}
printf("C:\n");
for(i=0;i<2;i++)
{
for(j=0;j<4;j++)
{
printf("%d\t",c[i][j]);
}
printf("\n");
}
}
I have no errors at compiling, but i get wrong numbers...awkward big numbers ... Any ideas?
Solution
Q: I have no errors at compiling, but i get wrong numbers...awkward big numbers ... Any ideas?
A: Yes - the moment you fork, you have two different processes with two completely independent address spaces :)
One good solution is to use threads instead of fork():
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow