11/28
Part 4 of 6 · A pool and a coordinatorLearn and do
Run the fetches on a pool with a fixed number of threads
Now bring the threads back, with a fixed number of them.
A thread pool is a fixed set of threads that take jobs from a queue
in flight, one on each worker u1u2u3u4
waiting in the pool's queue u5u6u7
Never more than 4 fetches in flight. The rest wait their turn, and the next one starts the moment a worker is free.
A thread pool is a fixed set of threads that take jobs from a queue. Python's is ThreadPoolExecutor(max_workers=n), from the concurrent.futures module.
When all n threads are busy, new jobs wait in the pool's queue until a thread is free. That queue now holds your frontier, and max_workers is your bound on fetches in flight. That bound is exactly what the tests measure.
submit gives you a future, and result() waits for it
from concurrent.futures import ThreadPoolExecutor
urls = [f"{E}/", f"{E}/a", f"{E}/c"]
with ThreadPoolExecutor(max_workers=2) as pool:
futures = [pool.submit(fetch, url) for url in urls]
for url, future in zip(urls, futures):
print(url, "has", len(future.result()), "links")
Three URLs on a pool of 2 threads, all submitted first. What do the three lines report?
Pick one to see what it prints.
Pick an answer above to see the rest