Command Palette

Search for a command to run...

Hectal
Back to the lesson: Topic 12.4 — Thread and Process Pools: concurrent.futures
Python · Example 2 of 2

wait, as_completed and timeouts on futures

Two futures are finished and one is pending. We sort the names because the order a set gives them is not guaranteed.

concurrent.futures gives you a pool of workers and a Future for every job you submit. ThreadPoolExecutor suits blocking I/O, ProcessPoolExecutor suits CPU-bound work, and both share the same simple API: submit, map and as_completed.

Change the code and press Run (Ctrl+Enter). Predict what will happen first, then break it on purpose and read what changes. Your edits are saved and match the lesson page.

Ready for more? This phase has 6 hands-on exercises with automatic checks.

Practice questions

Write the code in the editor, run it, then open the model answer to compare.

01

Create a Future, attach a callback that prints got 7, then set its result to 7.

02

Write first_error(futures) that returns the first exception stored in a list of finished futures, or None.

03

Write all_results(futures) that returns a list of results, with "failed" in place of any future that holds an exception.

Explain it without notes

01

What is a Future, and how does result() treat exceptions?

02

How do map and as_completed differ in the order of results?

03

When would you choose ThreadPoolExecutor over ProcessPoolExecutor, and the other way round?

04

How do you decide the size of a pool?

05

Inside a with ThreadPoolExecutor() block your code raises an exception after submitting 100 jobs. What happens to the jobs, and how would you stop them sooner?

wait, as_completed and timeouts on futures
Sign in to run this example in your browser.

Expected output

done: 2 | not done: 1
as_completed yielded: ['a', 'c']
b is not ready: TimeoutError