- Phase: 10. Concurrency & Internals
- Duration: 2.5 hours
- Create and manage processes with the multiprocessing module
- Bypass the GIL using separate processes
- Share data between processes with Value and Array
- Communicate via Queue and Pipe for IPC
- Use Pool for parallel task execution
- Decide between multiprocessing and threading
- multiprocessing module: Process, Pool, cpu_count
- bypassing GIL with processes
- Shared memory: Value, Array
- Queue and Pipe for IPC
- Process Pool for parallel execution
- Multiprocessing vs threading decision guide
- Performance comparison examples
Modules 000-091.
from multiprocessing import Process, Pool, cpu_count, Value, Array, Queue
from typing import List
# Basic process
def worker(name: str) -> None:
print(f"Process {name} running")
p = Process(target=worker, args=("P-1",))
p.start()
p.join()
# Process Pool
def square(n: int) -> int:
return n * n
with Pool(processes=cpu_count()) as pool:
results: List[int] = pool.map(square, range(10))
# Shared memory
counter = Value('i', 0)
arr = Array('d', [1.0, 2.0, 3.0])- Python multiprocessing documentation
- "Effective Python" concurrency items
- Python's multiprocessing guide: https://docs.python.org/3/library/multiprocessing.html
Module 093: Asynchronous Python: asyncio