AlgoViz

Semaphore

medium 45 min

A semaphore is a counter of permits with a waiting line.

Video lesson · Chapter 1 of 6

Make a prediction

0:00 / 4:38

See it run

Permits, the waiting line and who holds what, at run time.

Operations

Car park

Three spaces, five cars. Watch free and line.

Step 1 of 9

Open

gateFairSemaphorelimit3free3linenoneRedCarisoutsideBlueCarisoutsideGreenCarisoutsideYellowCarisoutsidePurpleCarisoutside

Three permits, nobody waits.

Step 1: Open

class FairSemaphore:    def acquire(self):        with self.lock:            if not self.line and self.free > 0:                self.free -= 1                return            me = Waiter()            self.line.append(me)        me.bell.wait()    def release(self):        with self.lock:            self.free += 1            if self.line:                first = self.line.popleft()                self.free -= 1                first.bell.set()
Watch
free and line
Result
Never more than 3 inside

When somebody waits, free does not rise on release: the permit changes hands.

In the real world

The same semaphore doing real jobs. Pick one and step through it.

One error without a finally, and the limit is smaller for ever.

Step 1 of 4

Two permits

AshaWorkerisreadyLeeWorkerisreadygateSemaphorefree2really held0

Two workers, two permits.

Step 1: Two permits

Common mistakes

The bugs interviewers watch for, with the fix beside each.

  • No finally

    critical

    One error, and the permit is lost for ever.

    Wrong
    gate.acquire()upload(file)gate.release()
    Right
    with gate:    upload(file)
  • Acquire inside the try

    critical

    If acquire fails, finally releases a permit that was never taken.

    Wrong
    try:    gate.acquire()    upload(file)finally:    gate.release()
    Right
    gate.acquire()try:    upload(file)finally:    gate.release()
  • Trusting it with the data

    critical

    N threads are inside together and change the same list.

    Wrong
    with gate:            # 3 permits    conn = idle.pop()    used.append(conn)
    Right
    with gate:    with lock:        conn = idle.pop()
  • Ignoring the answer

    critical

    After a timeout acquire returns False, and the code goes on as if it had a permit.

    Wrong
    gate.acquire(timeout=1)work()gate.release()
    Right
    if not gate.acquire(timeout=1):    raise Busy()try: work()finally: gate.release()
  • Deciding with the counter

    major

    Between looking and taking, another thread takes it.

    Wrong
    if gate.available() > 0:    gate.acquire()
    Right
    if gate.acquire(blocking=False):    ...
  • Two permits, one by one

    major

    Two jobs each hold one and wait for a second.

    Wrong
    gate.acquire()gate.acquire()
    Right
    gate.acquire(2)       # both or none

Interview tips

  • Start value

    • 1 for one at a time.
    • N for a limit.
    • 0 for a signal.
  • Give it back

    • A block or a guard object.
    • Acquire, then try.
    • Exactly as many as you took.
  • In a server

    • Always a timeout.
    • A short line.
    • Count full, late and failed apart.
  • Know the neighbours

    • Owner needed: a lock.
    • A condition: a monitor.
    • Per second: a rate limiter.
  • In depth

    • Sizes differ: strict line.
    • Size it: rate times time.
    • Across servers: lease and number.