1

I am trying to parallelize the addition of two simple 4x4 matrices. The child process adds only odd rows and the parents adds even ones. However, I can't seem to get the processes to work on shared pointer memory and the output is always given in halves, shown beneath the code:

#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>

int main() {
  int A[4][4] = {{1,2,3,4},{6,7,8,9},{11,12,13,14},{16,17,18,19}};
  int B[4][4] = {{1,2,3,4},{6,7,8,9},{11,12,13,14},{16,17,18,19}};
  int** C = (int**)malloc(sizeof(int)*4);
  for (int z = 0; z<4; z++) {
    C[z] = (int*)malloc(sizeof(int)*4);
  }
  pid_t cp;
  printf("Before fork\n");
  cp = fork();
  if (cp == 0) {
    for(int i = 1; i < 4; i+=2) {
      for(int j = 0; j < 4; j++) {
         printf("child process\n");
         printf("We are adding cell %d,%d\n",i,j);
         C[i][j] = A[i][j] + B[i][j];
         sleep(1);
      }
    }
  } else {
     for (int k = 0; k < 4; k+=2) {
        for(int l = 0; l < 4; l++) {
           printf("parent process\n");
           printf("We are adding cell %d,%d\n",k,l);
           C[k][l] = A[k][l] + B[k][l];
           sleep(1);
        }
     } 
  }
  sleep(10);
  printf("We are printing C here\n");
  for (int m = 0; m < 4; m++) {
      for(int n = 0; n < 4; n++) {
          printf("%d ",C[m][n]);
      }
      printf("\n");
  }
}

This is the output of the final for loop in the above code:

We are printing C here
0 0 0 0 
12 14 16 18 
0 0 0 0 
32 34 36 38 
We are printing C here
2 4 6 8 
0 0 0 0 
22 24 26 28 
0 0 0 0 
z.karl
  • 295
  • 2
  • 12
  • Possibly a [duplicate](https://stackoverflow.com/a/13274800/7034621)? `fork` copies the memory over, you'll have to create special, shared memory block for your approach to work. – orhtej2 Aug 21 '17 at 20:47

0 Answers0