C++ Soln. Solution to deadlock
Dining philosopher.\n\nclass DiningPhilosophers {\nprivate:\n    const int N = 5;\n    mutex fork[5];\npublic:\n    DiningPhilosophers() {\n        \n    }\n\n 
Dining philosopher.\n```\nclass DiningPhilosophers {\nprivate:\n    const int N = 5;\n    mutex fork[5];\npublic:\n    DiningPhilosophers() {\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        \n        //mutex &first_fork = fork[philosopher];\n        //mutex &second_fork = fork[(philosopher + 1) % N];\n\t\t\n        // The above could result in a deadlock. Consider the scenario.\n        // Let the philosophers be A, B, C, D, E. And the forks have ID\n        // 0, 1, 2, 3, 4, 5. Then:\n        // A requests 0 first, the B requests 1 first, i.e\n        // A->0, B->1, C->2, D->3, E->4.\n        // Note that this results in a cycle. Now when any of the philosophers\n        // try to pick up the other fork, they are acquired. This scenario\n        // results in starvation. \n\n        // This avoids the deadlock cycle if we look at the resource \n        // allocation graph.\n        mutex &first_fork = fork[min(philosopher, (philosopher + 1) % N)];\n        mutex &second_fork = fork[max(philosopher, (philosopher + 1) % N)];\n        \n        first_fork.lock();\n        pickRightFork();\n        second_fork.lock();\n        pickLeftFork();\n        eat();\n        putLeftFork();\n        second_fork.unlock();\n        putRightFork();\n        first_fork.unlock();\n    }\n};\n```
[]