A laundromat has washers identical machines; each customer is a thread.
Implement Laundromat(washers):
start_wash(timeout=None) -> bool: take a free machine and returnTrue, waiting if none is free. With atimeoutin seconds, give up after that long and returnFalse.finish_wash(): hand a machine back so a waiting customer can take it. Handing back more than were taken raisesValueErrorand 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.