CodeBlanks Logo Icon CodeBlanks

concurrent.futures

Learn pools with concurrent.futures.ThreadPoolExecutor.

What is concurrent.futures?

The concurrent.futures module provides a high-level interface for thread and process pools. ThreadPoolExecutor creates a pool of threads.

ex.submit(func) submits a task and returns a Future object. You get the result with future.result(); it waits until the computation finishes. The with ThreadPoolExecutor() as ex: block closes the pool automatically. This is more practical than managing Thread and Process by hand and is the recommended approach in modern Python.

submit and map

ThreadPoolExecutor provides two main methods: submit sends a single task, map applies a function to every item in a list.

submit is more flexible; you can send different functions and arguments. map is simpler; it applies one function to a data list and returns results in order. Both should be used inside a with block. For I/O-bound work (many network requests) ThreadPoolExecutor gives a big speedup.

Practice Run with ThreadPoolExecutor

Import with from concurrent.futures import ThreadPoolExecutor. Define a work function that returns "sonuc". Inside a with ThreadPoolExecutor() as ex: block do future = ex.submit(work) and write print(future.result()).

Starter code

main.py
# write the work function
# submit with the pool and get the result

Sample solution

main.py
from concurrent.futures import ThreadPoolExecutor

def work():
    return "result"

with ThreadPoolExecutor() as ex:
    future = ex.submit(work)
    print(future.result())

Expected output

sonuc

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Match concurrent.futures concepts

Term Meaning
ThreadPoolExecutor Thread pool
submit Submits a task
Future Result promise
result Gets the result

2 What does future.result() do?

main.py
with ThreadPoolExecutor() as ex:
    fut = ex.submit(func)
    val = fut.result()
  • Returns the result, waits until done Correct answer
  • Submits the task
  • Closes the pool
  • Raises an error

Explanation: answer: returns the result, waits until done. submit sends the task.

3 Complete the submit call

Question
with ThreadPoolExecutor() as ex:
    fut = ex.____(work)
Answer
with ThreadPoolExecutor() as ex:
    fut = ex.submit(work)

Explanation: ex.submit(func) submits a task.

All lessons in Expert