Back
+15 XP
Concept

Process Pools with ProcessPoolExecutor

`concurrent.futures.ProcessPoolExecutor` spawns separate OS worker processes. Each process has its own Python interpreter and GIL, achieving true multi-core CPU parallelism 🚀.

python
from concurrent.futures import ProcessPoolExecutor

def compute_square(n):
    return n * n

if __name__ == "__main__":
    with ProcessPoolExecutor(max_workers=2) as pool:
        results = list(pool.map(compute_square, [10, 20, 30]))
    print(results)  # [100, 400, 900] 🚀

# 50. Process Pools with ProcessPoolExecutor `concurrent.futures.ProcessPoolExecutor` spawns separate OS worker processes. Each process has its own Python interpreter and GIL, achieving true multi-core CPU parallelism 🚀. ```python from concurrent.futures import ProcessPoolExecutor def compute_square(n): return n * n if __name__ == "__main__": with ProcessPoolExecutor(max_workers=2) as pool: results = list(pool.map(compute_square, [10, 20, 30])) print(results) # [100, 400, 900] 🚀 ``` Always guard process spawning with `if __name__ == '__main__':` to prevent infinite recursive child process forks on Windows and macOS! 🚀 --- ### Question Why can ProcessPoolExecutor achieve true multi-core speedups where ThreadPoolExecutor cannot? 🧠 - [ ] a. Each worker process runs as an independent OS process with its own separate GIL 🚀 - [ ] b. It turns off CPU power throttling in the BIOS - [ ] c. Process pools share single-threaded memory without data serialization - [ ] d. It automatically moves all variables to GPU memory --- ### Challenge Write `def cube(n): return n ** 3`. Use `ProcessPoolExecutor(max_workers=2)` inside `if __name__ == '__main__':` to compute `list(executor.map(cube, [1, 2, 3]))`. Print the resulting list. 🎯 <details> <summary>Solution</summary> ```python from concurrent.futures import ProcessPoolExecutor def cube(n): return n ** 3 if __name__ == "__main__": with ProcessPoolExecutor(max_workers=2) as executor: results = list(executor.map(cube, [1, 2, 3])) print(results) ``` </details>

Checkpoint

Why can ProcessPoolExecutor achieve true multi-core speedups where ThreadPoolExecutor cannot? 🧠

Practice

Write `def cube(n): return n ** 3`. Use `ProcessPoolExecutor(max_workers=2)` inside `if __name__ == '__main__':` to compute `list(executor.map(cube, [1, 2, 3]))`. Print the resulting list. 🎯

Terminal
01
Tap code blocks below to assemble
Available Blocks