Junior — Middle
Which modules in the Python standard library are used for organizing parallel code execution?
sobes.tech AI
Answer from AI
The following modules are used in the Python standard library for organizing parallel code execution:
- threading — for creating and managing threads. Suitable for tasks with a large number of I/O operations.
- multiprocessing — for running multiple processes, which allows bypassing the GIL limitation and efficiently utilizing multiple CPU cores.
- concurrent.futures — a high-level interface for working with threads (ThreadPoolExecutor) and processes (ProcessPoolExecutor).
Example of using concurrent.futures for parallel function execution:
import concurrent.futures
def task(n):
return n * n
with concurrent.futures.ThreadPoolExecutor() as executor:
results = list(executor.map(task, range(5)))
print(results) # [0, 1, 4, 9, 16]