Condition Variable and mutex Locks
\n\n# Approach\n Describe your approach to solving the problem. \n\nJust use a mutex lock before picking and updating the fork. This is best practice to avoid i
\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\nJust use a mutex lock before picking and updating the fork. This is best practice to avoid in consistent results and race conditions.\n\n\n\n# Code\n```\nclass DiningPhilosophers {\npublic:\n\n    condition_variable cv[5] ;\n    mutex mtx ;\n    bool isFork[5] ;\n\n    DiningPhilosophers() {\n\n        for(int i=0;i<5;i++)\n        {\n            isFork[i]=true ;\n        }\n\n    }\n\n    void wantsToEat(int i,\n                    function<void()> pickLeftFork,\n                    function<void()> pickRightFork,\n                    function<void()> eat,\n                    function<void()> putLeftFork,\n                    function<void()> putRightFork) {\n        \n        unique_lock<mutex> lc1(mtx);\n\n       \n\n        if(isFork[i]==false)\n        {\n            cv[i].wait(lc1);\n        }\n\n        if(isFork[(i+1)%5]==false)\n            cv[(i + 1) % 5].wait(lc1);\n\n        pickLeftFork();\n        pickRightFork();\n        isFork[i]=false ;\n        isFork[(i+1)%5]=false ;\n\n        eat();\n\n        isFork[i]=true ;\n        isFork[(i+1)%5]=true ;\n        \n        putLeftFork();\n        putRightFork();\n\n        lc1.unlock();\n\n        cv[i].notify_all();\n        cv[(i + 1) % 5].notify_all();\n    }\n};\n```
['C++']