Design a parking lot
medium 90 minModel a car park with several levels as classes: vehicles, spaces of different sizes, tickets and a replaceable price rule.
Watch lesson4:48
Thread-safe space
One lock per space, and what it does not solve
The point: the change from free to taken must be one step that only one thread can win. Put the check and the act under the same lock.
Bug
What double booking looks like
With several gates, two threads can pass isAvailable() for the same space before either calls park. Reading is not wrong, and writing is not wrong. The pair is. This is check then act, also called time of check to time of use.
free = {"M3"}def gate(name): # a generator: each yield lets the other gate run if "M3" in free: # check yield f"{name} sees M3 free" free.discard("M3") # act yield f"{name} prints a ticket for M3" else: yield f"{name} shows FULL"north, south = gate("North"), gate("South")for step in (north, south, north, south): # the unlucky order print(next(step))yield is a moment where the other gate may run. This order happens rarely in real life, and every time here. Run it.Fix
A space that guards itself
from threading import Lockclass LockedSpot: def __init__(self, spot_id: str) -> None: self.id = spot_id self._lock = Lock() self._plate: str | None = None def try_park(self, plate: str) -> bool: with self._lock: # check and act under one lock if self._plate is not None: return False # someone was faster: not an error self._plate = plate return True def leave(self) -> str | None: with self._lock: plate, self._plate = self._plate, None return plate # who was here, for the billdef park_anywhere(spots: list[LockedSpot], plate: str) -> LockedSpot | None: for spot in spots: # the loser of a race simply tries the next one if spot.try_park(plate): return spot return Nonespots = [LockedSpot("M1"), LockedSpot("M2")]print(park_anywhere(spots, "A").id, park_anywhere(spots, "B").id, park_anywhere(spots, "C"))try_park answers yes or no. There is no public is_free, so nobody can build the bug again on top.final class LockedSpot { private final Object lock = new Object(); private Vehicle vehicle; // guarded by lock boolean tryPark(Vehicle v) { synchronized (lock) { if (vehicle != null) return false; vehicle = v; return true; } } /** Empties the space and says who was in it, which the bill needs. */ Vehicle removeVehicle() { synchronized (lock) { Vehicle removed = vehicle; vehicle = null; return removed; } }}synchronized (this) would let outsiders hold our lock.| Part | Why | Without it |
|---|---|---|
| Private lock object | Only this class can lock it | Somebody's synchronized (spot) around a slow call stops us |
| Check inside the lock | Check and act are one step | Double booking |
| Return false when taken | Losing a race is ordinary | Exceptions as traffic signs |
leave returns who was there | The bill needs it, and reading it later is another race | Two calls with a gap |
| No lock around final fields | Size and id never change | Wasted time, and a false feeling of safety |
Limits
What a lock per space does not do
- 1
It does not find
You still walk over the spaces and try one after another. With 500 spaces and a nearly full lot that is hundreds of locks for one car.
- 2
It does not count
Adding up 500 spaces takes 500 locks, and the sum belongs to no single moment.
- 3
It does not cover two spaces
A bus over five spaces needs five locks, taken in the same order by everybody, or two buses wait for each other for ever.
- 4
It does not protect the plate
The same car at two gates gets two spaces. Each space is perfectly safe.