Scarcity: limited resources
hard 50 minWhen more threads want something than there is of it, a design must say who gets it, who waits, for how long, and how it comes back.
Video lesson · Chapter 1 of 6
Make a prediction
See it run
Who gets it, who waits, for how long, and how it comes back.
Operations
Borrow and give back
One scanner, three people, one of them breaks it.
Step 1 of 8
First borrow
Nothing is free, but one may be made: alive becomes 1, then the scanner is made.
Step 1: First borrow
def borrow(self, timeout): with self._changed: able = lambda: self._free or self._alive < self._size if not self._changed.wait_for(able, timeout): raise PoolTimeout() if self._free: return Lease(self, self._free.pop()) self._alive += 1 return Lease(self, self._make())def _give_back(self, scanner, broken): with self._changed: if not broken: self._free.append(scanner) self._changed.notify() return scanner.close() self._forget() # alive - 1, notify all- Watch
- free and alive
- Result
- One user at a time
alive never goes above size.
In the real world
The same scarcity doing real jobs. Pick one and step through it.
One scanner a day is not given back.
Step 1 of 4
Monday
Three in the pool. A handler throws between take and give back.
Step 1: Monday
Common mistakes
The bugs interviewers watch for, with the fix beside each.
Give back without finally
criticalThe first error makes the pool smaller for good.
Wrongs = pool.take()s.scan(page)pool.put(s)Rightwith pool.borrow(5) as s: s.scan(page)Counting after making
criticalEverybody sees room before anybody counts.
Wrongscanner = make()self._alive += 1Rightself._alive += 1 # under the lockscanner = make() # outsideMaking with the lock held
majorNobody can give back while a slow object is made.
Wrongwith self._changed: return Lease(self, self._make())Rightwith self._changed: self._alive += 1return Lease(self, self._make())A line without a limit
criticalUnder overload everybody waits too long.
Wrongwaiting = Queue()Rightwaiting = Queue(maxsize=8)# full: refuse with a hintRelease in a finally around acquire
criticalIf acquire fails, somebody else's slot is freed.
Wrongtry: gate.enter(1) work()finally: gate.leave(took)Rightgate.enter(1)try: work()finally: gate.leave(took)Not looking at the line when someone gives up
majorThe next one sleeps beside free memory.
Wrongself._line.remove(t)return FalseRightself._line.remove(t)self._grant()return False
Interview tips
Four questions
- Who gets it?
- Who waits, how long?
- How does it come back?
Lend leases
- On every way out.
- Exactly once.
- Broken ones are closed.
Short lines
- Patience x slots / time.
- Refuse early.
- Give a time to return.
Size by numbers
- Rate x time held.
- Plus half.
- Shorten before you enlarge.