AlgoViz

Thread pool

medium 70 min

A 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

A deadlock in which the scarce thing is a worker. No lock is held, and Java's deadlock finder sees nothing.
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 limit on the wait makes the demonstration end: one parent gives up, and its worker can then run the other child. Without the limit the program hangs for ever.
Edit and run it in your browser

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

WayHowCost
Do not waitGive the child a continuation: when done, go on. The parent ends at onceCode in pieces, or async
Another poolParents in pool A, children in pool B, never backwardsMore threads, and an order of pools
Help while waitingThe waiting worker runs other tasks: fork and joinDeep stacks, surprising order, locks held across
Do it yourselfIf the child has not started, take it out and run it hereThe task must be claimable
The second row is a lock order for pools: A before B, always. A circle of pools is the same bug with more steps.
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()
First way: the parent never waits. One worker is enough for any number of parents.
Edit and run it in your browser
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 late
Fourth way: claim the child. Either a worker has it, or the parent runs it. Both cannot.
Edit and run it in your browser

The same illness elsewhere

PlaceScarce thingLooks like
Async code that blocksThe only event loop threadresult() on a coroutine, inside the loop
Node.js file calls4 threads of libuv by defaultAll slow DNS and file calls wait
Nested parallel streamsThe common pool of the processA library blocks in it, and everybody stops
Web server calls itselfIts own request threadsUnder load each request waits for another one