Advertisement
Guest User

rs thread semaphores

a guest
Nov 26th, 2014
137
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.29 KB | None | 0 0
  1. #include <stdlib.h>
  2. #include <stdio.h>
  3. #include <unistd.h>
  4. #include <pthread.h>
  5. #include <semaphore.h>
  6.  
  7. // Costanti di comodo
  8. #define FALSE 0
  9. #define TRUE 1
  10.  
  11.  
  12. pthread_mutex_t count_mutex = PTHREAD_MUTEX_INITIALIZER;
  13. sem_t count_sem;
  14. int count, n;
  15.  
  16. void init_vars (){
  17. // La coda è inizialmente vuota
  18. // Inizializzo i semafori
  19. count = 0;
  20. n = 3;
  21. sem_init (&count_sem, 0, 0);
  22. }
  23.  
  24. void* thread_function_count (void* arg){
  25. printf("Prima istruzione th: %s", my_id);
  26. pthread_mutex_lock (&count_mutex);
  27. count +=1;
  28. sem_post(&count_sem);
  29. pthread_mutex_unlock (&count_mutex);
  30. while(count != n){
  31. sem_wait(&count_sem);
  32. }
  33.  
  34. printf("Seconda istruzione th: %s", my_id);
  35. return NULL;
  36.  
  37. }
  38.  
  39.  
  40. int main(int argc, char* argv[]){
  41.  
  42. pthread_t T1_thread_id;
  43. char* T1_name = "t#1";
  44.  
  45. pthread_t T2_thread_id;
  46. char* T2_name = "t#2";
  47.  
  48. pthread_t T3_thread_id;
  49. char* T3_name = "t#3";
  50.  
  51. init_vars();
  52.  
  53. // Faccio partire i thread
  54. pthread_create(&T1_thread_id,NULL,&thread_function_count,(void*)T1_name);
  55. pthread_create(&T2_thread_id,NULL,&thread_function_count,(void*)T2_name);
  56. pthread_create(&T3_thread_id,NULL,&thread_function_count,(void*)T3_name);
  57.  
  58. pthread_join(T1_thread_id,NULL);
  59. pthread_join(T2_thread_id,NULL);
  60. pthread_join(T3_thread_id,NULL);
  61.  
  62. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement