Problems with C forks, wrong results, probably shared memory -


i have assignment matrix multiplication forks, using shared memory, compare time results multiplication without forks, here multiplication without them:

int matriza[am][an]; int matrizb[an][bp];  //here fill matrix .txt file  int matrizr[am][bp]; int a,b,c; (a=0; < am; a++){     (b = 0; b < bp; b++)     {         matrizr[a][b] = 0;         (c=0; c<an; c++){             matrizr[a][b] += matriza[a][c] * matrizb[c][b];          }     } } 

then try implement forks results wrong, im not sure if have implement shared memory , where, matriza, matrizb, , matrizr2 should shared? how this?

int matrizr2[am][bp]; pid_t pids[am][bp]; int h,j;  /* start children. */ty (h = 0; h < am; ++h) {     (j=0; j<bp ; ++j){       if ((pids[h][j] = fork()) < 0) {         perror("fork");         abort();       } else if (pids[h][j] == 0) {         matrizr2[h][j] = 0;         (c=0; c<an; c++){             matrizr2[h][j] += matriza[h][c] * matrizb[c][j];          }         printf("im fork %d,%d\n",h,j);         exit(0);       }     } } /* wait children exit. */ int status; pid_t pid; while (n > 0) {   pid = wait(&status);   --n;  } 

not giving complete solution because it’s homework assignment, functions use shared memory on unix documented here: http://pubs.opengroup.org/onlinepubs/009695399/functions/shmget.html

you call shmget() , pass identifier gives shmat(), in each child process, pointer shared memory.

one alternative have each process pass results in pipe, , copy them, slower. use threads instead of processes, since threads share memory. pass messages. memory-mapped file. shared memory cast pointer structure simplest way go, , has best performance.

finally, if writing same shared memory, need careful not let 2 processes write same memory. if open 1 process per row, , rows aligned, shouldn’t have issue, safe way use either locks or atomic variables.


Comments

Popular posts from this blog

html - Outlook 2010 Anchor (url/address/link) -

javascript - Why does running this loop 9 times take 100x longer than running it 8 times? -

Getting gateway time-out Rails app with Nginx + Puma running on Digital Ocean -