▶ Sign up free for the video, slides & prompts
The lesson below is open to all. Enter your email once to unlock every video, slide deck, prompt and code example on this device.
Checking…
Processes
Use every CPU core with multiprocessing.
🎬 Video version coming soon — read it now
For CPU-bound work, threads don't help much, because of the GIL. Processes do: each one is a separate Python interpreter with its own GIL, so they truly run in parallel on different CPU cores.
How many cores do you have?
ProcessPoolExecutor
On an 8-core laptop the parallel version is often 4–7 times faster. Not exactly 8, because starting processes and moving data between them takes time.
The __main__ guard is required
On Windows and macOS, each new process re-imports your script. Without if __name__ == "__main__":, every child would try to start its own pool, which crashes or loops. Always put pool code under the guard. That's the guard from Files, Modules & Packages, now essential.
Run this as a .py script from the terminal. Process pools can behave oddly in notebooks, and Colab has only a couple of cores anyway.
The cost: copying data
Processes don't share memory. Arguments and results are copied between processes (pickled). So:
- Send small inputs and get small outputs: a file path, not the file's contents
- Give each process a big chunk of work, not millions of tiny tasks. Use
pool.map(func, items, chunksize=1000)for long lists of small jobs - Functions must be defined at the top level of a module (not lambdas) so they can be sent to other processes
Which tool for which job
- Waiting on network, disk or APIs: threads or asyncio
- Heavy pure-Python calculation: processes
- Heavy numeric calculation: first try NumPy or pandas. They're often faster than parallel pure Python, and some already use multiple cores internally
- Truly huge data: tools like Polars, Dask or Spark, beyond this course
In one line
ProcessPoolExecutor runs CPU-heavy Python on all cores; guard it with __main__, keep data transfer small and give each process substantial work.
Share with a friend