Beats 83.3% runtime & 100% memory - C++ using only semaphores
The key idea is to wait(left), wait(right), eat, release(left), release(right), think... repeat.\n\nBut if all 5 philosophers decides to eat at once, we can dea
The key idea is to wait(left), wait(right), eat, release(left), release(right), think... repeat.\n\nBut if all 5 philosophers decides to eat at once, we can deadlock.\n\nOptions:\n- Only allow 4 philosophers to eat at once, so there is always 1 extra fork to allow one philospher to start eating.\n- Alternate picking left or right fork first depending on whether philosopher idex is odd or even to avoid deadlock (method I used).\n\n```\n#include <semaphore.h>\n\n#define NUM_PHILOSOPHERS 5\n#define LEFT (philosopher)\n#define RIGHT ((philosopher + 4) % NUM_PHILOSOPHERS)\n\nclass DiningPhilosophers {\nprivate:\n    sem_t semPhil[NUM_PHILOSOPHERS];\n\npublic:\n    DiningPhilosophers() {\n        for (int i = 0; i < NUM_PHILOSOPHERS; i++) {\n            sem_init(&semPhil[i], 0, 1);\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        int first = (philosopher % 2 == 0) ? LEFT : RIGHT;\n        int second = LEFT + RIGHT - first;\n\n        sem_wait(&semPhil[first]);\n        sem_wait(&semPhil[second]);\n\n        pickLeftFork();\n        pickRightFork();\n        eat();\n        putLeftFork();\n        putRightFork();\n        \n        sem_post(&semPhil[first]);\n        sem_post(&semPhil[second]);\n    }\n};\n```
[]