Semaphore
medium 45 minA semaphore is a counter of permits with a waiting line.
Video lesson · Chapter 1 of 6
Make a prediction
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
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
Two workers, two permits.
Step 1: Two permits
Common mistakes
The bugs interviewers watch for, with the fix beside each.
No finally
criticalOne error, and the permit is lost for ever.
Wronggate.acquire()upload(file)gate.release()Rightwith gate: upload(file)Acquire inside the try
criticalIf acquire fails, finally releases a permit that was never taken.
Wrongtry: gate.acquire() upload(file)finally: gate.release()Rightgate.acquire()try: upload(file)finally: gate.release()Trusting it with the data
criticalN threads are inside together and change the same list.
Wrongwith gate: # 3 permits conn = idle.pop() used.append(conn)Rightwith gate: with lock: conn = idle.pop()Ignoring the answer
criticalAfter a timeout acquire returns False, and the code goes on as if it had a permit.
Wronggate.acquire(timeout=1)work()gate.release()Rightif not gate.acquire(timeout=1): raise Busy()try: work()finally: gate.release()Deciding with the counter
majorBetween looking and taking, another thread takes it.
Wrongif gate.available() > 0: gate.acquire()Rightif gate.acquire(blocking=False): ...Two permits, one by one
majorTwo jobs each hold one and wait for a second.
Wronggate.acquire()gate.acquire()Rightgate.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.