progress

~/problems / Coordination / Semaphore

Laundromat washers

On a phone? Coding is easier on a laptop: email this problem to yourself . Meanwhile: quiz this topic or fight a boss.

easy ~15 min

A laundromat has washers identical machines; each customer is a thread.

Implement Laundromat(washers):

  • start_wash(timeout=None) -> bool: take a free machine and return True, waiting if none is free. With a timeout in seconds, give up after that long and return False.
  • finish_wash(): hand a machine back so a waiting customer can take it. Handing back more than were taken raises ValueError and changes nothing.
shop = Laundromat(2)
shop.start_wash()             # True
shop.start_wash()             # True
shop.start_wash(timeout=0.1)  # False after about 0.1s: both machines busy
shop.finish_wash()
shop.start_wash(timeout=0.1)  # True right away
shop.finish_wash(); shop.finish_wash()
shop.finish_wash()            # ValueError: all 2 machines are already free

Never more than washers customers washing, and a waiting customer gets a returned machine right away. washers >= 1. Don't sleep or busy-wait.

Show hint

threading.BoundedSemaphore(washers) does it all: acquire(timeout=timeout) returns False on timeout, and release() raises ValueError past the starting value.

Topic: Semaphore. Counting access to N resources; producer/consumer.

Read the visual guide
0:00
Ctrl ' run · Ctrl ↵ submit
esc