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 6 test cases (3 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 →```
class TrafficLight:
current: int = 1 # 1 = N-S green, 2 = E-W green
lock: Mutex
def carArrived(self, roadId, turnGreen, crossCar):
with self.lock:
if self.current != roadId:
turnGreen()
self.current = roadId
crossCar()
```
The mutex makes the read-modify-write of `current` atomic. Without it, two cars from different directions could both observe `current != roadId`, both turn green, and both proceed - a collision.
We do not need separate per-direction queues; mutual exclusion alone is enough. Throughput could be improved with a fairness scheme (e.g. let up to K cars from the active direction through before honouring a waiting opposite car) but that's an extension.
Why it's interesting: the trap candidates fall into is using two separate mutexes (one per direction) - that allows the cross-direction violation. The whole intersection is one critical section.
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.