Sobes.tech
Junior — Middle

How do you implement working with high-level abstractions, such as using thread pools?

sobes.tech AI

Answer from AI

To work with high-level abstractions such as task pools, Python often uses the concurrent.futures or multiprocessing modules.

For example, a thread pool (ThreadPoolExecutor) allows running multiple tasks in parallel, managing the number of threads:

from concurrent.futures import ThreadPoolExecutor
import time

def task(n):
    time.sleep(1)
    return n * n

with ThreadPoolExecutor(max_workers=3) as executor:
    results = list(executor.map(task, range(5)))

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

This approach allows abstracting from low-level thread or process management, simplifying parallel task execution.