Implementation in C++ || mutex || synchronization
IntuitionThe Dining Philosophers problem is a classic synchronization problem. We need to ensure mutual exclusion (only one philosopher can hold a fork at a tim
# Intuition
<!-- Describe your first thoughts on how to solve this problem. -->
The Dining Philosophers problem is a classic synchronization problem. We need to ensure mutual exclusion (only one philosopher can hold a fork at a time), deadlock prevention, and starvation prevention.
***Deadlock Avoidance:-***
Odd philosophers pick right fork first, even philosophers pick left fork first.
This breaks circular dependency and prevents deadlocks.

***Starvation Prevention:-***
Mutexes ensure that only one philosopher can use a fork at a time.
Philosophers alternate between thinking and eating, ensuring fairness.

***Thread Safety:-***
mutex forks[5] ensures that multiple threads do not simultaneously access the same fork.
# Approach
<!-- Describe your approach to solving the problem. -->
To avoid deadlocks, a common strategy is:

- Even-numbered philosophers pick the left fork first, then the right.
- Odd-numbered philosophers pick the right fork first, then the left.
- Using mutexes, we ensure safe fork access.
# Complexity
- Lock & Unlock operations: $$O(1)$$ (constant time)
- Total function calls per philosopher: $$O(n) $$(since each calls the function $$𝑛$$ times)
- Overall Complexity: $$O(n)$$ per philosopher.

# Code
```cpp []
class DiningPhilosophers {
public:
    mutex forks[5]; // Mutex for each fork

    DiningPhilosophers() {}

    void wantsToEat(int philosopher,
                    function<void()> pickLeftFork,
                    function<void()> pickRightFork,
                    function<void()> eat,
                    function<void()> putLeftFork,
                    function<void()> putRightFork) {
        
        int left = philosopher;                   // Left fork index
        int right = (philosopher + 1) % 5;        // Right fork index

        // Odd philosophers pick right fork first, Even philosophers pick left first
        if (philosopher % 2 == 0) {
            forks[left].lock();
            forks[right].lock();
        } else {
            forks[right].lock();
            forks[left].lock();
        }

        // Pick up forks
        pickLeftFork();
        pickRightFork();
        
        eat();
        
        // Put down forks
        putLeftFork();
        putRightFork();
        
        // Unlock forks
        forks[left].unlock();
        forks[right].unlock();
    }
};

```
['Concurrency', 'C++']