Advertisement
Guest User

Untitled

a guest
Dec 9th, 2019
78
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.45 KB | None | 0 0
  1. #include <bits/stdc++.h>
  2. #include <semaphore.h>
  3. #include <pthread.h>
  4. #include <unistd.h>
  5. #define N 3
  6. using namespace std;
  7.  
  8. pthread_t m_counter[N];
  9. pthread_t m_monitor;
  10. pthread_t m_collector;
  11. //sem_t read_sem; //forces mutual exclusion on read
  12. sem_t write_sem; //forces mutual exclusion on writes
  13. int messages_cnt = 0;
  14.  
  15. void* counter_update_count(void* counter_index)
  16. {
  17. sleep(rand()%100);
  18. int* x = (int*) counter_index;
  19. cout << "Counter thread [" << *x <<"] received a message" << endl;
  20. sem_wait(&write_sem);
  21. cout << "Counter thread[" << *x <<"] : waiting to write" << endl;
  22. messages_cnt++;
  23. cout << "Counter thread[" << *x <<"] : now adding to counter, counter value = " << messages_cnt << endl;
  24. sem_post(&write_sem);
  25. return 0;
  26. }
  27. void* mointor_update_count(void*)
  28. {
  29. cout << "Monitor thread waiting to read counter";
  30. sleep(rand()%100);
  31. sem_wait(&write_sem);
  32. cout << "Monitor thread reading a count of " << messages_cnt << endl;
  33. messages_cnt = 0;
  34. //cout << "Monitor thread waiting to write" << endl;
  35. sem_post(&write_sem);
  36. return 0;
  37. }
  38.  
  39. int main()
  40. {
  41. sem_init(&write_sem, 0, 1);
  42. for(int i = 0; i < N; ++i)
  43. {
  44. pthread_create(&m_counter[i],NULL,counter_update_count,(void*)(&i));
  45. }
  46. pthread_create(&m_monitor, NULL,mointor_update_count, NULL);
  47. for(int i = 0; i < N; ++i)
  48. {
  49. pthread_join(m_counter[i],NULL);
  50. }
  51. pthread_join(m_monitor, NULL);
  52. return 0;
  53. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement