Advertisement
Guest User

Untitled

a guest
Apr 27th, 2017
91
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 0.96 KB | None | 0 0
  1. #include <stdlib.h>
  2. #include <stdio.h>
  3. #include <pthread.h>
  4. #include <semaphore.h>
  5. #include <time.h>
  6. int postiLiberi=200;//Risorsa condivisa
  7.                     //Esclusivo
  8.  
  9. pthread_mutex_t mutex1;
  10.  
  11. void *cassa(void *arg){
  12.    
  13.     pthread_mutex_lock(&mutex1); //Istruzione bloccante
  14.    
  15.     //sezione critica
  16.     int posti;
  17.    
  18.    
  19.     posti=1+rand()%10;//Operazione di I/O
  20.     if(posti<=postiLiberi){
  21.         printf("Posti liberi %d\n",postiLiberi);
  22.         postiLiberi-=posti; //prenotazione posti
  23.         printf("Posti prenotati %d\n",posti);
  24.        
  25.         }else{
  26.        
  27.         printf("Posti non disponibili\n"); 
  28.            
  29.             }
  30.     pthread_mutex_unlock(&mutex1);
  31.    
  32.     pthread_exit(0); //Termina il thread
  33.     }
  34.  
  35. int main(int argc, char **argv)
  36. {
  37.     pthread_mutex_unlock(&mutex1); //Init sbloccata di mutex1
  38.     pthread_t tid[200];
  39.     int i=0;
  40.     srand(time(0));
  41.     do{
  42.         pthread_create(&tid[i],NULL,cassa,NULL);
  43.        
  44.         i++;
  45.         }while(postiLiberi>0&&i<200);
  46.    
  47.     for(i=0;i<200;i++){
  48.         pthread_join(tid[i],NULL);
  49.         }
  50.    
  51.     return 0;
  52. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement