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 mostmax_workersthreads. - Return
(station, value)for the first call to succeed by clock time, not list position. Calls that raise are ignored; if all raise, raiseLookupError. - 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.