SHARE
TWEET

Ese mutex

totore1990 Jan 22nd, 2019 (edited) 63 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <unistd.h>
  4. #include <pthread.h>
  5.  
  6. ///Inizializzo la var di condizione e un mutex
  7.  
  8. pthread_mutex_t mutex1 = PTHREAD_MUTEX_INITIALIZER;
  9. pthread_mutex_t mutex2 = PTHREAD_MUTEX_INITIALIZER;
  10. pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
  11.  
  12. int **matrice;
  13. int n;
  14. int pos[2]={-1,-1};
  15. int finito=0;
  16. int elem_ricerca = 5;
  17. void* trova (void* riga)
  18. {
  19.     int *i = (int *)riga;
  20.     int j;
  21.     for(j=0;j<n;j++)
  22.     {
  23.         pthread_mutex_lock(&mutex1);
  24.         if(finito)
  25.             pthread_exit((void*) 0);
  26.         pthread_mutex_unlock(&mutex1); 
  27.         if(matrice[*i][j]==elem_ricerca)
  28.         {
  29.             pthread_mutex_lock(&mutex1);
  30.             finito=1;
  31.             pos[0]=*i;
  32.             pos[1]=j;
  33.             printf("\nPos elemento trovato: [%2d] [%2d]\n",pos[0],pos[1]);
  34.             ///pthread_cond_signal(&cond);
  35.             pthread_mutex_unlock(&mutex1); 
  36.         }
  37.     }  
  38.     pthread_exit((void*) 0);
  39.    
  40.    
  41. }
  42.  
  43. /*void *stampa_trovato ( )
  44. {
  45.     pthread_mutex_lock(&mutex2);
  46.     pthread_cond_wait(&cond,&mutex2);
  47.     pthread_mutex_unlock(&mutex2);
  48.     printf("\nPos elemento trovato: [%2d] [%2d]\n",pos[0],pos[1]);
  49.     pthread_exit((void*) 0);
  50. }*/
  51.  
  52.  
  53. int main(int argc,char**argv)
  54. {
  55.     int n = atoi(argv[1]);
  56.     pthread_t *tid;
  57.     tid = (pthread_t *) malloc((n)*sizeof(pthread_t));
  58.     int i,j;
  59.     ///Alloco la matrice
  60.     matrice = (int **) malloc(n*sizeof(int *));
  61.     for(i=0;i<n;i++)
  62.         matrice[i] = (int *) malloc(n*sizeof(int));
  63.     for(i=0;i<n;i++)
  64.         for(j=0;j<n;j++)
  65.             matrice[i][j]=i*n+j+1;
  66.     ///Creo il thread Stampa_trovato
  67.     /*pthread_create(&tid[n],NULL,stampa_trovato,(void*) 0);*/
  68.     ///Creo i thread di controllo righe
  69.     for(i=0;i<n;i++)
  70.         pthread_create(&tid[i],NULL,trova,(void *) &i);
  71.     for(i=0;i<n;i++)
  72.         pthread_join(tid[i],0);
  73.    
  74. }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top