Advertisement
Diamyx

SO lab7 ex2

Nov 20th, 2019
143
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.03 KB | None | 0 0
  1. #include <unistd.h>
  2. #include <stdlib.h>
  3. #include <stdio.h>
  4. #include <pthread.h>
  5. #include <errno.h>
  6. #include <semaphore.h>
  7. pthread_mutex_t mtx;
  8. sem_t sem;
  9. int n = 5, count;
  10.  
  11. typedef struct thread
  12. {
  13.     pthread_t thr;
  14.     int id;
  15. }thread;
  16.  
  17. struct thread th[5];
  18.  
  19. void barrier_point()
  20. {
  21.  
  22.     pthread_mutex_lock(&mtx);
  23.     count++;
  24.     pthread_mutex_unlock(&mtx);
  25.  
  26.     if(count < n)
  27.     {
  28.         sem_wait(&sem);
  29.     }
  30.     else
  31.     {
  32.         for(int i = 0; i < n; i++) sem_post(&sem);
  33.     }
  34. }
  35.  
  36. void* tfun(void* v)
  37. {
  38.     int id = *(int*) v;
  39.  
  40.     printf("%d reached the barrier\n", id);
  41.     barrier_point();
  42.     printf("%d passed the barrier\n", id);
  43.  
  44.     return NULL;
  45. }
  46.  
  47. int main()
  48. {
  49.     if(pthread_mutex_init(&mtx,NULL))
  50.     {
  51.         perror(NULL);
  52.         return errno;
  53.     }
  54.  
  55.     if(sem_init(&sem, 0, 0))
  56.     {
  57.         perror(NULL);
  58.         return errno;
  59.     }
  60.     for(int i = 0; i < n; i++)
  61.     {
  62.         th[i].id = i;
  63.         pthread_create(&th[i].thr, NULL, tfun, &th[i].id);
  64.     }
  65.  
  66.     for(int i = 0; i < n; i++) pthread_join(th[i].thr, NULL);
  67.  
  68.     pthread_mutex_destroy(&mtx);
  69.     sem_destroy(&sem);
  70.  
  71.     return 0;
  72. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement