Sobes.tech
Junior — Middle

What is included in the 'concurrent' module of Python's standard library?

sobes.tech AI

Answer from AI

In Python's standard library, the concurrent module contains the futures submodule, which provides a high-level interface for asynchronous task execution.

Main components:

  • concurrent.futures.ThreadPoolExecutor — allows executing tasks in a thread pool, which is convenient for I/O operations.
  • concurrent.futures.ProcessPoolExecutor — executes tasks in a process pool, useful for CPU-intensive operations.
  • The Future class — an object representing the result of an asynchronous operation, allowing to retrieve the result or handle exceptions.

Example of using ThreadPoolExecutor:

from concurrent.futures import ThreadPoolExecutor

def task(n):
    return n * n

with ThreadPoolExecutor(max_workers=3) as executor:
    futures = [executor.submit(task, i) for i in range(5)]
    results = [f.result() for f in futures]

print(results)  # [0, 1, 4, 9, 16]