Process Pool (Pool, map, starmap)
Why use a process pool
Section titled “Why use a process pool”Creating many processes manually is not ideal.
A pool:
- reuses worker processes
- makes parallel execution easier
Pool.map
Section titled “Pool.map”from multiprocessing import Pool
def square(x: int) -> int:
return x * x
if __name__ == "__main__":
with Pool(processes=4) as pool:
results = pool.map(square, [1, 2, 3, 4, 5])
print(results)Pool.starmap (multiple arguments)
Section titled “Pool.starmap (multiple arguments)”from multiprocessing import Pool
def power(x: int, p: int) -> int:
return x ** p
if __name__ == "__main__":
with Pool(processes=2) as pool:
results = pool.starmap(power, [(2, 3), (3, 2), (4, 2)])
print(results)Common mistakes
Section titled “Common mistakes”- Forgetting the
if __name__ == "__main__"guard. - Passing non-picklable objects (like lambdas on some platforms).
🧪 Try It Yourself
Section titled “🧪 Try It Yourself”Exercise 1 – Start a Process
Section titled “Exercise 1 – Start a Process”Exercise 2 – Process Pool map()
Section titled “Exercise 2 – Process Pool map()”Exercise 3 – Multiprocessing Queue
Section titled “Exercise 3 – Multiprocessing Queue”pch.coffeeTagline
pch.coffeeCtapch.feedbackHeading
pch.feedbackSubheading