The classic Dining Philosophers Problem is a fundamental concurrency challenge that illustrates the complexities of resource sharing in multithreaded environments.
The Setup: Five philosophers sit around a circular table, each with a bowl of spaghetti. Between each pair of adjacent philosophers lies a single fork. To eat, a philosopher must acquire both the fork to their left and the fork to their right.
The Challenge: Design a thread-safe solution where philosophers can alternate between thinking and eating without causing deadlock or starvation. Each philosopher is represented by a separate thread, and multiple philosophers may want to eat simultaneously.
Your Task: Implement the wantsToEat() method that coordinates the philosopher's actions:
philosopher: ID of the philosopher (0-4) who wants to eatpickLeftFork()andpickRightFork(): Functions to acquire forkseat(): Function called when both forks are acquiredputLeftFork()andputRightFork(): Functions to release forks
Constraints: The solution must be deadlock-free and ensure no philosopher starves while maintaining thread safety for concurrent access.
Input & Output
Visualization
Time & Space Complexity
Constant time operations for mutex acquisition
Only requires mutexes for forks, no additional space
Constraints
- Exactly 5 philosophers numbered 0 to 4
- Each philosopher must acquire both adjacent forks to eat
- Solution must be deadlock-free and starvation-free
- Multiple threads may call wantsToEat() concurrently
- Fork operations are atomic and thread-safe