NicolaDelPrete

Sum POSIX

Jul 14th, 2019
84
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 0.99 KB | None | 0 0
  1. #include <pthread.h>
  2. #include <semaphore.h>
  3. #include <stdio.h>
  4. #include <stdlib.h>
  5. #include <sys/stat.h>
  6. #include <fcntl.h>
  7.  
  8. #define SEM_VALORE "/valore"
  9.  
  10. int m=5;
  11. int min=90000;
  12. int *matrice;
  13. sem_t *valore;
  14.  
  15. void *somma (void *i)
  16. {
  17.     sem_wait(valore);
  18.     int j,indice,somma=0;
  19.     indice=*(int*)i;
  20.     if(indice%2==0)
  21.     {
  22.         j=0;
  23.         while(j<m)
  24.         {
  25.             somma=somma + (*matrice+indice*m+j);
  26.             j=j+2;
  27.         }
  28.     }else
  29.     {
  30.         j=1;
  31.         while(j<m)
  32.         {
  33.             somma= somma + (*matrice+indice*m+j);
  34.             j=j+2;
  35.         }
  36.     }
  37.     if(somma<min)
  38.         min=somma;
  39.     sem_post(valore);
  40. }
  41.  
  42. int main ()
  43. {
  44.     int i,j;
  45.     pthread_t riga[m];
  46.         valore=sem_open(SEM_VALORE,O_CREAT|O_EXCL,077,1);
  47.     matrice=(int*)calloc(m*m,sizeof(int));
  48.     for(i=0;i<m;i++)
  49.     { for(j=0;j<m;j++)
  50.         *(matrice+i*m+j)=rand()%256;
  51.     }
  52.     for(i=0;i<m;i++)
  53.         { pthread_create(&riga[i],NULL,somma,(void*)&i);}
  54.     sleep(5);
  55.     printf("%d\n",min);
  56.     for(i=0;i<m;i++)
  57.         pthread_join(riga[i],NULL);
  58.     sem_unlink(SEM_VALORE);
  59.     free(matrice);
  60.     return 0;
  61. }
Add Comment
Please, Sign In to add comment