AlgoViz

Design a parking lot

medium 90 min

Model 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

RuleCheck
No space is sold twiceSpaces on active tickets are all different
No space is lostfree + active = total, when nothing is in progress
One car, one ticketPlates on active tickets are all different
It fitsspace size at least the smallest size
One bill, one chargeNumber 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"]))
2000 random steps with a fixed seed: the same every time. Break leave (forget the append) and it tells you in a few steps. It has one thread, so it finds wrong logic and not races.
Edit and run it in your browser

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)
A clock as the hook: it is called between the claim and the end of 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.
Edit and run it in your browser

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
For a real Python, since a browser has no threads. The barrier makes all eight start together, 200 rounds make a lucky one unlikely, and the checks are the rules and not a printed number.
Mistake in a stress testWhy it hides races
Start threads in a loopThe first has finished before the third starts
One roundOne order out of many
Print insideOutput has its own lock and puts the threads in a row
Assert in the threadThe failure dies with the thread; the test is green
8 spaces for 8 carsNobody competes. Use fewer spaces than cars
No time limitA deadlock looks like a slow test

Level 4

The slow and the broken

FakeTest
Card machine that declines onceTicket is back, space still taken, then one charge
Card machine that charges and then times outRetry with the same key: one charge
Card machine that blocks for everOther gates still enter: the lock is not held
Clock at 59:59 and 60:00One hour, one hour; 60:01 is two
Clock in the October nightFour hours, not three
Listener that raisesThe 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.