Junior — Middle
When running on a server with 8 or 16 cores, what allows faster task execution – a thread or a goroutine?
sobes.tech AI
Answer from AI
The standard library modules in Python for parallel code execution include:
- threading — for creating and managing threads. Suitable for I/O-bound tasks.
- multiprocessing — for running multiple processes, which can bypass the GIL and utilize multiple CPU cores effectively.
- concurrent.futures — a high-level interface for working with thread pools (
ThreadPoolExecutor) and process pools (ProcessPoolExecutor).
Example using concurrent.futures for parallel 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]