How to make a matrix sum using shared memory?

Asked

Viewed 447 times

0

I need help to perform a sum of matrices using shared memory.

#define LINHAS 3
#define COLUNAS 3
#define PULAR_LINHA printf("\n")

int main(int argc, char *argv[])
{

  int linha, coluna;    //indices
  int pid, id;
  int matriz1[][COLUNAS] = { {1,2,3}, {4,5,6}, {7,8,9} };
  int matriz2[][COLUNAS] = { {3,5,3}, {4,5,6}, {7,8,9} };
  int segmento, status;
  segmento = shmget(IPC_PRIVATE, sizeof(int)*18, IPC_CREAT | IPC_EXCL | S_IRUSR | S_IWUSR);
  int *matrizSolucao = (int*)shmat(segmento, NULL, 0);
  id = fork();

  if (id == 0)  // Processo filho
  {
        for(linha = 0; linha < LINHAS; linha++)
        {
            for(coluna = 0; coluna < COLUNAS; coluna++)
            printf("%d\t", *matrizSolucao);
            printf("\n");
        }
  }
  else          // Processo pai
  {
        pid = wait(&status);
        for(linha = 0; linha < LINHAS; linha++)
        {
            for(coluna = 0; coluna < COLUNAS; coluna++)
            *matrizSolucao = matriz1[linha][coluna] + matriz2[linha][coluna];
        }
  }
  //Libera a mmoria compartilhada do processo
  shmdt(matrizSolucao);
  //Libera a memoria compartilhada
  shmctl(segmento, IPC_RMID, 0);
  return EXIT_SUCCESS;
}

With this code the matrix actually appears, but with all its values zeroed, can someone help? Thank you.

2 answers

1

In your code, the child process prints; the parent process calculates.
The parent process waits for the child to finish before calculating, so the child process prints zeros.

Exchange father and son process codes.

  • Thanks for the information, I reversed the code of the parent and child process, but now instead of zeros is printing only 18, I checked that it is only doing the sum of the last positions and putting this result in the whole matrix, which can be?

  • the instruction *matrizSolucao = matriz1[linha][coluna] + matriz2[linha][coluna]; always write in the same space.

0

From what I saw in the code you do:

*matrizSolucao = matriz1[linha][coluna] + matriz2[linha][coluna]

I believe you are always putting the sum in the first position, or every sum you make will be going to the first position and not going each one to its right position.

And when you do:

for(linha = 0; linha < LINHAS; linha++)
{
    for(coluna = 0; coluna < COLUNAS; coluna++)
        printf("%d\t", *matrizSolucao);
        printf("\n");
}

You are again printing the first position every time.

And on the zeroes is what the pmd said up there about the son being inverted with the father.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.