progress

~/problems / Pools & pipelines / Thread pool / concurrent crawler

Fastest weather station wins

On a phone? Coding is easier on a laptop: email this problem to yourself . Meanwhile: quiz this topic or fight a boss.

easy ~15 min

A sailing app needs the wind speed. Several weather stations report it, but they're flaky: some answer fast, some slowly, some raise. Any one good answer will do.

Implement first_reading(stations, read, max_workers) -> tuple:

  • Call read(station) on a thread pool of at most max_workers threads.
  • Return (station, value) for the first call to succeed by clock time, not list position. Calls that raise are ignored; if all raise, raise LookupError.
  • Return as soon as you have an answer: don't wait for slow stations, and don't start ones that haven't started.
# read("north") takes 0.5s -> 12;  read("pier") takes 0.05s -> 9;  read("hill") raises at once
first_reading(["north", "pier", "hill"], read, 3)   # ("pier", 9) after ~0.05s
first_reading(["hill"], read, 1)                    # LookupError
first_reading([], read, 2)                          # LookupError

max_workers >= 1; up to 100 stations.

Show hint

submit all, loop over concurrent.futures.as_completed(futures), and return the first with future.exception() of None. A with ThreadPoolExecutor(...) block waits for every running call on exit, so create the pool yourself and call pool.shutdown(wait=False, cancel_futures=True) before returning.

Topic: Thread pool / concurrent crawler. ThreadPoolExecutor, asyncio, thread-safe visited set.

Read the visual guide
0:00
Ctrl ' run · Ctrl ↵ submit
esc