Advertisement
Dany1858

S.O. Scritto 22-01-2014

Jun 8th, 2015
565
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.91 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <pthread.h>
  3. #include <semaphore.h>
  4.  
  5. #define K 10
  6. #define N 20
  7.  
  8.         /*semafori globali*/
  9. sem_t A, B, C;
  10.  
  11.         /*dichiaro la struttura globale dei thread*/
  12. struct thread{
  13.     int ID;
  14.     int tipo;
  15. };
  16.  
  17.         /*dichiaro le funzioni*/
  18. void *elabora1(void *);
  19. void elabora2(struct thread);
  20. int esito(struct thread);
  21.  
  22.  
  23. int main()
  24. {
  25.         /*inizializzo le variabili*/
  26. int i=0;
  27. int tipo;
  28. pthread_t thread_id[1000]; //mi servirà poi per attendere che finiscano tutti
  29.                            //i thread prima di terminare il main
  30.  
  31. struct thread thRd[1000];
  32.  
  33.         /*inizializzo i semafori*/
  34. sem_init(&A, 0, K);
  35. sem_init(&B, 0, 1);
  36. sem_init(&C, 0, 1);
  37.  
  38. //creo a random il tipo di thread
  39. while(i<N){
  40.     thRd[i].ID=i;
  41.     thRd[i].tipo=rand()%2;
  42.     pthread_create(&thread_id[i], NULL, &elabora1, &thRd[i]);
  43.     printf("\nThread n: %d creato", i); i++; sleep(5);}
  44.  
  45. i=0;
  46. while(i<N){
  47. pthread_join(thread_id[i], NULL);
  48. i++;}
  49. printf("\n\n");
  50. }
  51.  
  52.         /*definisco le funzioni*/
  53. void *elabora1(void *p)
  54. {
  55. struct thread *thr=p;
  56. if(thr->tipo==0){
  57.         /*Sezione critica*/
  58.     sem_wait(&A);
  59.  
  60.         /*Elaborazione*/
  61.     printf("\nThread n: %d sta usando la risorsa A", thr->ID);
  62.     sleep(3);
  63.  
  64.         /*fine sezione critica*/
  65.     sem_post(&A);}
  66. else{
  67.         /*sezione critica*/
  68.     sem_wait(&A);
  69.     sem_wait(&B);
  70.  
  71.  
  72.         /*Elaborazione*/
  73.     printf("\nThread n: %d sta usando le risorse A e B", thr->ID);
  74.     sleep(5);
  75.  
  76.         /*invoco esito*/
  77.     if(esito(*thr)==0){
  78.        
  79.         /*fine sezione critica*/
  80.         sem_post(&A);
  81.         sem_post(&B);}
  82.     else{
  83.         elabora2(*thr);
  84.         sem_post(&A);
  85.         sem_post(&B);}}
  86. printf("\nIl thread n: %d ha terminato l'elaborazione", thr->ID);
  87. }
  88.  
  89. int esito(struct thread thr)
  90. {      
  91.         /*Elaborazione*/
  92. printf("\nThread n: %d sta elaborando l'esito", thr.ID);
  93. sleep(5);
  94. return (rand() %2);
  95. }
  96.  
  97. void elabora2(struct thread thr)
  98. {
  99. sem_wait(&C);
  100.  
  101.         /*Elaborazione*/
  102. printf("\nThread n: %d sta usando la risorsa C", thr.ID);
  103. sleep(3);
  104. sem_post(&C);
  105. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement