Advertisement
GerONSo

Untitled

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