Thread pool
medium 70 minA few threads that live long, one queue with a limit, and a loop: take, run, repeat.
Watch lesson5:06
Waiting for itself
A deadlock without a lock, and four ways out
The point: if a task waits for another task of the same pool, enough such tasks take every worker, and the ones they wait for can never start.
See it
Two workers, two parents, no child
The pool starves
Python
import threadingfrom concurrent.futures import ThreadPoolExecutor, TimeoutErrordef run(workers): pool = ThreadPoolExecutor(max_workers=workers) both_in = threading.Barrier(2) def parent(name): both_in.wait(2) # both parents hold a worker child = pool.submit(len, name) try: return child.result(timeout=0.3) except TimeoutError: return "stuck" answers = [f.result() for f in [pool.submit(parent, n) for n in ("ann", "bo")]] pool.shutdown() return answersprint("2 workers:", run(2))print("3 workers:", run(3))The second line is the trap. With three workers it works, so the test passes, and with three parents at once it hangs again. No number is safe unless you know how many parents can be active.
Out
Four ways out
| Way | How | Cost |
|---|---|---|
| Do not wait | Give the child a continuation: when done, go on. The parent ends at once | Code in pieces, or async |
| Another pool | Parents in pool A, children in pool B, never backwards | More threads, and an order of pools |
| Help while waiting | The waiting worker runs other tasks: fork and join | Deep stacks, surprising order, locks held across |
| Do it yourself | If the child has not started, take it out and run it here | The task must be claimable |
Python
from concurrent.futures import Future, ThreadPoolExecutorpool = ThreadPoolExecutor(max_workers=1)def parent(name): answer = Future() child = pool.submit(len, name) child.add_done_callback(lambda c: answer.set_result(c.result() * 10)) return answer # the worker is free againouter = [pool.submit(parent, n) for n in ("ann", "bo")]print([f.result(2).result(2) for f in outer])pool.shutdown()Python
import threadingclass Claimable: def __init__(self, fn): self._fn, self._once = fn, threading.Lock() self._done, self.value = threading.Event(), None def try_run(self): if not self._once.acquire(blocking=False): return False # somebody else has it try: self.value = self._fn() finally: self._done.set() return True def join(self): if not self.try_run(): self._done.wait() # it is really running elsewhere return self.valuechild = Claimable(lambda: 42) # in the queue, no worker is freeprint(child.join())print(child.try_run()) # a worker comes too lateThe same illness elsewhere
| Place | Scarce thing | Looks like |
|---|---|---|
| Async code that blocks | The only event loop thread | result() on a coroutine, inside the loop |
| Node.js file calls | 4 threads of libuv by default | All slow DNS and file calls wait |
| Nested parallel streams | The common pool of the process | A library blocks in it, and everybody stops |
| Web server calls itself | Its own request threads | Under load each request waits for another one |