bugfree Icon
interview-course
interview-course
interview-course
interview-course
interview-course
interview-course
interview-course
interview-course

Leetcode Problem 1226. The Dining Philosophers

1226. The Dining Philosophers

Leetcode Solutions

Semaphore with Mutex Locks

  1. Initialize a semaphore with a count of 4 to allow a maximum of four philosophers to pick up forks simultaneously.
  2. When a philosopher wants to eat, they first call wait() on the semaphore to decrease the count.
  3. If the semaphore count is greater than zero, the philosopher proceeds to pick up the forks; otherwise, they wait.
  4. The philosopher picks up the left fork and then the right fork, each time using a mutex lock to ensure exclusive access to the fork.
  5. After picking up both forks, the philosopher calls the eat() function.
  6. The philosopher puts down the right fork and then the left fork, again using mutex locks to ensure exclusive access.
  7. The philosopher calls signal() on the semaphore to increase the count, allowing another philosopher to proceed.
  8. Repeat steps 2-7 as necessary.
UML Thumbnail

Odd-Even Philosopher Approach

Ask Question

Programming Language
image/screenshot of info(optional)
Full Screen
Loading...

Suggested Answer

Answer
Full Screen
Copy Answer Code
Loading...