Items 6 and 7 never ran because the iterator that Executor.map returns cancels the calls still waiting for a worker when it stops early.
The fix is the batch's fix: catch inside the function the pool runs, so the pool only ever sees return values.
def run_batch(tables, steps, workers=1):
check(steps)
def one(table):
try:
return apply(table, steps)
except Exception as error:
return error
with ThreadPoolExecutor(max_workers=workers) as pool:
return list(pool.map(one, tables))
The with block shuts the pool down when it ends. It waits for every call, so no thread outlives the function.
one reads steps and its own table and writes nothing shared, so it needs no lock. A lock, threading.Lock(), lets one thread at a time run the code inside with lock:, so two threads can't interleave a read and a write of the same object. The moment workers write to something shared, like a counter or a cache, they need one.
A function can build another function and return it. The inner def can use the outer function's arguments even after the outer one has returned:
def adder(n):
def add(x):
return x + n
return add
plus2 = adder(2)
print(plus2(5))
7
adder(2) returns add, which still knows that n is 2. A function together with the names it remembers is a closure.
In the editor, write catching(fn). It returns a new function that calls fn and returns the exception instead of raising it. tenth(k) is a small worker that divides by k - 2, so it raises at k = 2, and the last line runs it on a pool.