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

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.

LockSemaphore
Holders1N
Released byThe thread that has itAny thread. A car leaves through another gate
Question it answersMay I touch this data?Is there one left?
WaitingFor the holderFor a permit, with a time limit if you like
OrderFair mode on requestFair mode on request: new Semaphore(n, true)

Trap

One semaphore for each size, the naive way

Java
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();}
Looks right. Three bugs.

And the repairs

  1. 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. 2

    Remember which permit

    The size of the space is on the ticket. Give back that one, never the vehicle's own.

  3. 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

Python
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())
One size. A permit means that a space is in the queue, so 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.
Edit and run it in your browser

Waiting at the barrier

Full lot

Four ways to say no

AnswerCodeWhen
No, at onceacquire(blocking=False)A road with traffic behind the car
Wait a littleacquire(timeout=120)A lane with room for a few cars
A bounded queue, then noQueue with a maximum, for example 5You know how many cars the lane holds
Go there insteadAsk a neighbouring lotTwo lots, one sign
Whatever you choose, show it before the driver turns in. An honest no at the street is better than a long yes at the barrier. Regular customers with a reservation have their own pool of permits.

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.