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
Testing the races
Rules, unlucky orders, and stress
The point: a race does not show up because you run the code often. Make the unlucky order on purpose, then check rules that must always hold, and use stress as the third net.
Rules
What must always be true
| Rule | Check |
|---|---|
| No space is sold twice | Spaces on active tickets are all different |
| No space is lost | free + active = total, when nothing is in progress |
| One car, one ticket | Plates on active tickets are all different |
| It fits | space size at least the smallest size |
| One bill, one charge | Number of charges = number of receipts |
Level 1
Random work against the rules
Python
import randomdef check(make_lot, kinds, steps=2000, seed=7): """Random work, and after each step the rules that must always hold.""" rnd, lot, total = random.Random(seed), *make_lot() inside = {} for n in range(steps): if inside and rnd.random() < 0.45: ticket_id = rnd.choice(list(inside)) lot.leave(ticket_id) del inside[ticket_id] else: ticket = lot.enter(f"P{n}", rnd.choice(kinds)) if ticket: inside[ticket[0]] = ticket[1] # id -> space assert len(set(inside.values())) == len(inside), "one space, two tickets" assert lot.free() + len(inside) == total, "a space was lost" return "ok"class TinyLot: def __init__(self, spaces): self._free, self._by_id, self._next = list(range(spaces)), {}, 1 def enter(self, plate, kind): if not self._free: return None ticket = (self._next, self._free.pop()) self._by_id[ticket[0]] = ticket[1] self._next += 1 return ticket def leave(self, ticket_id): self._free.append(self._by_id.pop(ticket_id)) def free(self): return len(self._free)print(check(lambda: (TinyLot(5), 5), ["car"]))leave (forget the append) and it tells you in a few steps. It has one thread, so it finds wrong logic and not races.Level 2
The unlucky order, on purpose
Put a hook between the check and the act, and let the test run the other gate there. Generators, as on the first page of this level, or a fake pool whose claim calls back. The test fails every time with the old code and passes every time with the new one. That is worth more than a thousand lucky runs.
Python
from threading import Lockclass Lot: def __init__(self, now): self._lock, self._now, self._free = Lock(), now, ["M3"] def enter(self): with self._lock: spot = self._free.pop() if self._free else None return (spot, self._now()) if spot else Noneseen = []lot = Nonedef clock(): seen.append(lot._lock.locked()) # called in the middle of enter return 900lot = Lot(clock)print(lot.enter(), lot.enter(), seen)enter. A second car may try to enter at exactly that moment. The check says that the lock is held then, so it must wait. Prints True once: the second call finds no space and never asks the clock.Level 3
Stress, done properly
Python
from concurrent.futures import ThreadPoolExecutorfrom threading import Barrierdef test_no_space_is_given_twice(): for _ in range(200): # one lucky run proves nothing lot = make_lot(medium=3, large=1) start = Barrier(8) def arrive(i): start.wait() # all eight leave the line together return lot.enter(Vehicle(f"CAR-{i}", VehicleType.CAR)) with ThreadPoolExecutor(8) as pool: tickets = [t for t in pool.map(arrive, range(8)) if t] assert len(tickets) == 4 # four spaces fit a car assert len({t.spot.id for t in tickets}) == 4 # and all are different assert sum(lot.free().values()) == 0| Mistake in a stress test | Why it hides races |
|---|---|
| Start threads in a loop | The first has finished before the third starts |
| One round | One order out of many |
| Print inside | Output has its own lock and puts the threads in a row |
| Assert in the thread | The failure dies with the thread; the test is green |
| 8 spaces for 8 cars | Nobody competes. Use fewer spaces than cars |
| No time limit | A deadlock looks like a slow test |
Level 4
The slow and the broken
| Fake | Test |
|---|---|
| Card machine that declines once | Ticket is back, space still taken, then one charge |
| Card machine that charges and then times out | Retry with the same key: one charge |
| Card machine that blocks for ever | Other gates still enter: the lock is not held |
| Clock at 59:59 and 60:00 | One hour, one hour; 60:01 is two |
| Clock in the October night | Four hours, not three |
| Listener that raises | The other signs still change |
How do you show that your lot is thread-safe?
BreaksRun it and see
- How
- Start ten threads, print, look.
- Limit
- Green on your laptop, red in production on a machine with more cores.
- Choose when
- Never as proof.
WorksStress with a barrier and rules
- How
- As above, hundreds of rounds.
- Limit
- Finds likely races only. When it fails it is hard to repeat.
- Choose when
- Always, in addition.
StrongArgue, then force the order
- How
- State which lock guards which fields. One deterministic test for each gap you closed. Then stress.
- Limit
- You need to see the gap to test it.
- Choose when
- Here. The argument in one sentence: every field of the lot is read and written under its lock.