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
Many gates and floors
Splitting the lock, and the new problems
The point: split a lock along the line where the data is already split. Here that is the level. Then say what you gave up: the exact total.
Design
The level earns its class
When a level becomes a class
1/3One lock per level
In the small design a level is a number on the space. Now it owns a lock and its own free spaces. It has state and behaviour, so it has earned a class.
usesowns (dies together)implements
from collections import dequefrom dataclasses import dataclassfrom threading import Lock@dataclass(frozen=True)class Spot: id: str level: intclass Level: """Now a level is a class: it has its own lock and its own free spaces.""" def __init__(self, number: int, spot_count: int) -> None: self.number = number self._lock = Lock() self._free = deque(Spot(f"{number}-{i}", number) for i in range(1, spot_count + 1)) def claim(self) -> Spot | None: with self._lock: return self._free.popleft() if self._free else None def release(self, spot: Spot) -> None: with self._lock: self._free.appendleft(spot) def looks_free(self) -> int: return len(self._free) # a hint for the order, never a promiseclass Lot: def __init__(self, levels: list[Level]) -> None: self._levels = {level.number: level for level in levels} def claim(self, gate_level: int) -> Spot | None: order = sorted(self._levels.values(), key=lambda l: (l.looks_free() == 0, abs(l.number - gate_level))) for level in order: spot = level.claim() # decides, with that level's lock only if spot: return spot return None def release(self, spot: Spot) -> None: self._levels[spot.level].release(spot)lot = Lot([Level(0, 1), Level(1, 1), Level(2, 1)])print([lot.claim(gate_level=0).id, lot.claim(gate_level=2).id, lot.claim(gate_level=2).id, lot.claim(gate_level=0)])looks_free, read without a lock). The decision uses the lock. A wrong hint costs one more try, never a wrong answer.Policies
Which level first?
| Order | Good | Bad |
|---|---|---|
| Lowest first | Simple, short walks | All gates fight for level 0 |
| Nearest to the gate | Gates on different levels never meet | Level 0 fills first anyway |
| Emptiest first | Spreads cars and locks | Longer drives; every gate runs to the same emptiest level |
| Round robin | Spreads evenly, no reading | Ignores distance |
| Random of two, take the emptier | Spreads nearly as well as emptiest, without the herd | Harder to explain to a driver |
New problems
What splitting breaks
- 1
The total is no longer one moment
Adding five levels while cars move may show a total that never existed. Fine for a sign. If it must be exact, take all locks in level order, or keep one counter with its own lock.
- 2
A space can be missed
A gate looked at level 0 (full), then a car left it, then the gate looked at levels 1 to 4 (full) and said full. One space was free. Try once more before saying no, or accept it: the next car gets it.
- 3
The plate check spans levels
It is not a fact of one level. Keep it in its own concurrent set with an atomic
add:if (!inside.add(plate)) refuse. If no space is found, or something fails, remove it again. - 4
Deadlock becomes possible
Two locks held by two threads in two orders. Rule: never hold two level locks, and if you must, always lowest first.
How do you spread the work of many gates?
BreaksA lock for each gate
- How
- Every gate has its own lock and calls the same pool.
- Limit
- It protects nothing that is shared.
- Choose when
- Only for the gate's own hardware.
WorksOne lock
- How
- As in the base design.
- Limit
- In theory a bottleneck. In numbers: 0.00085% busy.
- Choose when
- Until a measurement says otherwise.
StrongA lock for each level
- How
- Level owns pool and lock; hints choose the order; the plate set is separate.
- Limit
- Totals are soft, a space can be missed, more to test.
- Choose when
- Levels are already separate in the data, or claims do more work than a pop.
Beyond
When one process is not enough
| Step | Truth lives in | Claim is |
|---|---|---|
| One machine in the booth | Memory, with tickets on disk | A pop under a lock |
| Gates are separate machines | A database | One conditional update, check the row count |
| The network to the database fails | Each level's controller has its own spaces | Local pop; totals are sent later |
| Many car parks | One database for each, one service for search | The same, per lot. Search shows hints |