[c++] mutex only (textbook solution)
we can change the rules by numbering the forks 1 through 5 and insisting that the philosophers pick up the fork with the lower number first. The philosopher who
we can change the rules by numbering the forks 1 through 5 and insisting that the philosophers pick up the fork with the lower number first. The philosopher who is sitting between fork 1 and 2 and the philosopher who is sitting between forks 1 and 5 must now reach for the same fork first (fork 1) rather than picking up the one on the right. Whoever gets fork 1 first is now free to take another one. Whoever doesn\'t get fork 1 must now wait for the first philosopher to release it. Deadlock is not possible.\n\n```\nclass DiningPhilosophers {\n    int n;\n    vector<std::mutex> fork_locks; \npublic:\n    DiningPhilosophers() {\n        n = 5;\n        fork_locks = vector<std::mutex>(n);\n    }\n\n    void wantsToEat(int philosopher,\n                    function<void()> pickLeftFork,\n                    function<void()> pickRightFork,\n                    function<void()> eat,\n                    function<void()> putLeftFork,\n                    function<void()> putRightFork) {\n\t\tint left_id = philosopher % n;\n        int right_id = (philosopher+1) % n;\n\n        if (philosopher % n == 1) {\n            fork_locks[right_id].lock();\n            fork_locks[left_id].lock();\n            pickRightFork();\n            pickLeftFork();\n            eat();\n            putLeftFork();\n            putRightFork();\n            fork_locks[left_id].unlock();\n            fork_locks[right_id].unlock();\n        } else {\n            fork_locks[left_id].lock();\n            fork_locks[right_id].lock();\n            pickRightFork();\n            pickLeftFork();\n            eat();\n            putLeftFork();\n            putRightFork();\n            fork_locks[right_id].unlock();\n            fork_locks[left_id].unlock();\n        }\n    }\n};\n```
[]