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
Semaphore capacity
Counting permits, and waiting for one
The point: a semaphore counts and lets callers wait. It does not know which space. Use it when someone should wait at the barrier instead of hearing no.
Tool
What a semaphore adds
A lock has one holder. A counting semaphore has N permits: acquire takes one or waits, release gives one back. A lot with N equal spaces maps to it directly, and no code walks over spaces to know whether there is room.
| Lock | Semaphore | |
|---|---|---|
| Holders | 1 | N |
| Released by | The thread that has it | Any thread. A car leaves through another gate |
| Question it answers | May I touch this data? | Is there one left? |
| Waiting | For the holder | For a permit, with a time limit if you like |
| Order | Fair mode on request | Fair mode on request: new Semaphore(n, true) |
Trap
One semaphore for each size, the naive way
boolean tryPark(Vehicle vehicle) { if (!total.tryAcquire()) return false; Semaphore own = forSize(vehicle.minSize()); if (!own.tryAcquire()) { // a car, and no medium space is left total.release(); return false; // 1. large spaces are free, and the car is refused } return true; // 2. it says yes, but not which space}void release(Vehicle vehicle) { forSize(vehicle.minSize()).release(); // 3. a car that stood in L1 gives back a medium permit total.release();}And the repairs
- 1
Try the sizes upwards
Take a permit of the smallest size that fits, else of the next one. The same fallback as the pool.
- 2
Remember which permit
The size of the space is on the ticket. Give back that one, never the vehicle's own.
- 3
No separate total
Two counters for one truth, and a refusal between them. The total is the sum.
Right
Permit first, then the space
from collections import dequefrom threading import Lock, Semaphoreclass WaitingPool: """One size. A semaphore counts, the queue says which space it is.""" def __init__(self, spot_ids: list[str]) -> None: self._permits = Semaphore(len(spot_ids)) self._lock = Lock() self._free = deque(spot_ids) def claim(self, wait_seconds: float = 0) -> str | None: got = self._permits.acquire(timeout=wait_seconds) if wait_seconds else self._permits.acquire(blocking=False) if not got: return None with self._lock: return self._free.popleft() # cannot be empty: we hold a permit def release(self, spot_id: str) -> None: with self._lock: self._free.append(spot_id) # the space first self._permits.release() # then the permission to take itpool = WaitingPool(["M1"])print(pool.claim(), pool.claim())pool.release("M1")print(pool.claim())popleft cannot fail. That promise holds only because release puts the space back before the permit. Swap these two lines and a waiting driver wakes up to an empty queue.Waiting at the barrier
Full lot
Four ways to say no
| Answer | Code | When |
|---|---|---|
| No, at once | acquire(blocking=False) | A road with traffic behind the car |
| Wait a little | acquire(timeout=120) | A lane with room for a few cars |
| A bounded queue, then no | Queue with a maximum, for example 5 | You know how many cars the lane holds |
| Go there instead | Ask a neighbouring lot | Two lots, one sign |
Do you need a semaphore here?
BreaksAs a check before the claim
- How
if (permits.availablePermits() > 0), then claim.- Limit
- Check then act again. The number is old when you read it.
- Choose when
- Never. The number is for a sign.
WorksNo semaphore
- How
- The pool returns nothing when empty, under the lot's lock.
- Limit
- Nobody can wait. The driver tries again.
- Choose when
- The base design. One mechanism instead of two.
StrongA semaphore for each size, for waiting
- How
- Permit, then pop; push, then release. Time limit and fair mode.
- Limit
- Two structures that must agree, so they live in one class and nowhere else.
- Choose when
- The requirement says wait.