Concurrent Futures With Timeout Handling
Run IO-bound tasks on a thread pool, collect results as they finish, and cancel or report stragglers when the global timeout fires.
Code
import time
from concurrent.futures import FIRST_COMPLETED, ThreadPoolExecutor, TimeoutError, wait
def fetch(source: str) -> str:
delays = {'fast': 0.05, 'medium': 0.15, 'slow': 0.8}
time.sleep(delays.get(source, 0.1))
return f"data-from-{source}"
def main() -> None:
sources = ['fast', 'medium', 'slow']
deadline = time.monotonic() + 0.5 # 全局预算 500ms
with ThreadPoolExecutor(max_workers=4) as pool:
pending = {pool.submit(fetch, s): s for s in sources}
while pending:
remaining = max(0, deadline - time.monotonic())
done, pending = wait(pending, timeout=remaining,
return_when=FIRST_COMPLETED)
if not done:
print('deadline hit; cancelling stragglers')
for future in pending:
future.cancel()
break
for future in done:
print(f'{future.result()}')
if __name__ == '__main__':
main()How it works
Concurrent Futures With Timeout Handling keeps everything in the functions fetch and main.
Iteration happens inside while pending — everything outside it runs once. From concurrent it pulls FIRST_COMPLETED, ThreadPoolExecutor, TimeoutError, wait — the imports name exactly which library surface the snippet touches.
Watch out for
- Plan for an install step:
concurrentis a real dependency, resolved by the package manager.
Putting it to use
The primary signature is def fetch(source: str) -> str
The run prints deadline hit; cancelling stragglers — each prefix names the step that produced it.
Core lines
return f"data-from-{source}"
def main() -> None:
sources = ['fast', 'medium', 'slow']
deadline = time.monotonic() + 0.5 # 全局预算 500ms
with ThreadPoolExecutor(max_workers=4) as pool:
pending = {pool.submit(fetch, s): s for s in sources}
def fetch(source: str) -> str:
delays = {'fast': 0.05, 'medium': 0.15, 'slow': 0.8}
time.sleep(delays.get(source, 0.1))
return f"data-from-{source}"
Interactive Tools for This Topic
FAQ
- Does this require external packages?
- Yes — `concurrent`. Add it to your project before running the snippet.
Report a problem with this exampleOpens a pre-filled issue on GitHub.