[Python3] semaphore
\n\nfrom threading import Semaphore, Lock\n\nclass DiningPhilosophers:\n    \n    def __init__(self):\n        self.counter = Semaphore(4)\n        self.locks =
\n```\nfrom threading import Semaphore, Lock\n\nclass DiningPhilosophers:\n    \n    def __init__(self):\n        self.counter = Semaphore(4)\n        self.locks = [Lock() for _ in range(5)]\n\n    # call the functions directly to execute, for example, eat()\n    def wantsToEat(self,\n                   philosopher: int,\n                   pickLeftFork: \'Callable[[], None]\',\n                   pickRightFork: \'Callable[[], None]\',\n                   eat: \'Callable[[], None]\',\n                   putLeftFork: \'Callable[[], None]\',\n                   putRightFork: \'Callable[[], None]\') -> None:\n        with self.counter: \n            with self.locks[philosopher], self.locks[(philosopher-1) % 5]: \n                pickLeftFork()\n                pickRightFork()\n                eat()\n                putLeftFork()\n                putRightFork()\n```\n\n**Approach 2 -- prefer small number**\n```\nfrom threading import Lock\n\nclass DiningPhilosophers:\n    \n    def __init__(self):\n        self.locks = [Lock() for _ in range(5)]\n\n    # call the functions directly to execute, for example, eat()\n    def wantsToEat(self,\n                   philosopher: int,\n                   pickLeftFork: \'Callable[[], None]\',\n                   pickRightFork: \'Callable[[], None]\',\n                   eat: \'Callable[[], None]\',\n                   putLeftFork: \'Callable[[], None]\',\n                   putRightFork: \'Callable[[], None]\') -> None:\n        small, large = min(philosopher, (philosopher + 1) % 5), max(philosopher, (philosopher + 1) % 5)\n        with self.locks[small]: \n            with self.locks[large]: \n                pickLeftFork()\n                pickRightFork()\n                eat()\n                putLeftFork()\n                putRightFork()\n```\n\nImplemented in C++\n```\nclass DiningPhilosophers {\n    vector<mutex> locks; \npublic:\n    DiningPhilosophers() {\n        locks = vector<mutex>(5); \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 small = min(philosopher, (philosopher+1) % 5), large = max(philosopher, (philosopher+1) % 5); \n        locks[small].lock(); \n        locks[large].lock(); \n        pickLeftFork(); \n        pickRightFork(); \n        eat(); \n        putLeftFork(); \n        putRightFork(); \n        locks[large].unlock(); \n        locks[small].unlock(); \n    }\n};\n```
['Python3']