We use cookies for site analytics. Accept to help us understand how the site is used. See our Privacy Policy for details.
A hard concurrency problem, graded against 3 test cases (1 of them hidden).
Coordinating threads with locks, semaphores, and condition variables.
Reach for it when you see: Ordering guarantees between threads, bounded buffers, or classic synchronisation puzzles.
More Concurrencyproblems →Number the forks 0..4. Philosopher `i` always picks up `min(left, right)` first, then `max(left, right)`. Because there is a strict acquisition order across the whole system, no cycle can form in the wait-for graph - and Coffman's circular-wait condition is broken, so the system is deadlock-free.
```
philosopher(i):
while True:
think()
l, r = i, (i + 1) % 5
first, second = (l, r) if l < r else (r, l)
forks[first].lock()
forks[second].lock()
eat()
forks[second].unlock()
forks[first].unlock()
```
Other valid schemes: Chandy-Misra (each philosopher requests forks from neighbours), or limit concurrent eaters to 4 with a counting semaphore.
Simulation walkthrough
Starvation isn't a concern in this small grader - we just need a feasible deadlock-free schedule. The simulation does single-step "bites": a philosopher with both forks free is added to the output and immediately releases. Adjacent philosophers can never both be in the eating set within the same step, so the output never has neighbours back-to-back.
The full reference solution in every supported language stays in the editor above - reveal it there once you have had a real attempt.
Read off this problem's own test suite, so these are the cases a submission actually has to survive.
These apply to the pattern as a whole, not just this problem.