Advertisement
GerONSo

Untitled

Dec 14th, 2021
20
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.31 KB | None | 0 0
  1. #include <iostream>
  2. #include <thread>
  3. #include <chrono>
  4. #include <vector>
  5. #include "semaphore.cpp"
  6.  
  7. std::vector<Semaphore> forkes(5);
  8. std::vector<int> currentPhilosopher(5, -1);
  9. std::mutex global_mutex;
  10.  
  11. enum PrintType {
  12. START_THINK, END_THINK, START_EAT, END_EAT
  13. };
  14.  
  15. void print(PrintType type, int philosopher_id) {
  16. // std::lock_guard<decltype(global_mutex)> lock(global_mutex);
  17. switch (type) {
  18. case START_THINK:
  19. printf("[%d] started thinking", philosopher_id);
  20. case END_THINK:
  21. printf("[%d] ended thinking", philosopher_id);
  22. case START_EAT:
  23. printf("[%d] started eating", philosopher_id);
  24. case END_EAT:
  25. printf("[%d] ended eating", philosopher_id);
  26. }
  27. printf(", current forkes busyness is [%lu, %lu, %lu, %lu, %lu], current fork distribution is [%d, %d, %d, %d, %d]\n",
  28. forkes[0].getCount(),
  29. forkes[1].getCount(),
  30. forkes[2].getCount(),
  31. forkes[3].getCount(),
  32. forkes[4].getCount(),
  33. currentPhilosopher[0],
  34. currentPhilosopher[1],
  35. currentPhilosopher[2],
  36. currentPhilosopher[3],
  37. currentPhilosopher[4]);
  38. }
  39.  
  40. void eat(int philosopher_id) {
  41. using namespace std::literals;
  42.  
  43. print(START_THINK, philosopher_id);
  44. forkes[philosopher_id].acquire();
  45. currentPhilosopher[philosopher_id] = philosopher_id;
  46. forkes[(philosopher_id + 1) % 5].acquire();
  47. currentPhilosopher[(philosopher_id + 1) % 5] = philosopher_id;
  48. print(END_THINK, philosopher_id);
  49.  
  50. print(START_EAT, philosopher_id);
  51. std::this_thread::sleep_for(1s);
  52. print(END_EAT, philosopher_id);
  53. forkes[philosopher_id].release();
  54. currentPhilosopher[philosopher_id] = -1;
  55. forkes[(philosopher_id + 1) % 5].release();
  56. currentPhilosopher[(philosopher_id + 1) % 5] = -1;
  57. eat(philosopher_id);
  58. }
  59.  
  60. int main() {
  61. for (int i = 0; i < 5; ++i) {
  62. forkes[i].release();
  63. }
  64. std::vector<std::thread> philosophers;
  65. for (int i = 0; i < 5; ++i) {
  66. std::thread philosopher = std::thread(eat, i);
  67. philosophers.push_back(std::move(philosopher));
  68. }
  69. for (int i = 0; i < philosophers.size(); ++i) {
  70. philosophers[i].join();
  71. }
  72. return 0;
  73. }
  74.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement