Advertisement
den4ik2003

Untitled

Aug 31st, 2023
83
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.98 KB | None | 0 0
  1. #include "philosopher.hpp"
  2.  
  3. #include <twist/test/inject_fault.hpp>
  4.  
  5. namespace dining {
  6.  
  7. Philosopher::Philosopher(Table& table, size_t seat)
  8. : table_(table),
  9. seat_(seat),
  10. left_fork_(table_.LeftFork(seat)),
  11. right_fork_(table_.RightFork(seat)) {
  12. }
  13.  
  14. void Philosopher::Eat() {
  15. AcquireForks();
  16. EatWithForks();
  17. ReleaseForks();
  18. }
  19.  
  20. // Acquire left_fork_ and right_fork_
  21. void Philosopher::AcquireForks() {
  22. if (seat_ % 2 == 0) {
  23. right_fork_.lock();
  24. left_fork_.lock();
  25. } else {
  26. left_fork_.lock();
  27. right_fork_.lock();
  28. }
  29. }
  30.  
  31. void Philosopher::EatWithForks() {
  32. table_.AccessPlate(seat_);
  33. // Try to provoke data race
  34. table_.AccessPlate(table_.ToRight(seat_));
  35. ++meals_;
  36. }
  37.  
  38. // Release left_fork_ and right_fork_
  39. void Philosopher::ReleaseForks() {
  40. right_fork_.unlock();
  41. left_fork_.unlock();
  42. }
  43.  
  44. void Philosopher::Think() {
  45. // Random pause or context switch
  46. twist::test::InjectFault();
  47. }
  48.  
  49. } // namespace dining
  50.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement