Part 13 / Topic 5 of 11
multiprocessing
The multiprocessing module runs functions in separate processes. Each process is a full copy of Python with its own memory and its own GIL, so CPU work really runs in parallel on several cores. Its API looks just like threading.
Like opening four separate kitchens, each with its own knife: more setup, but all four chop at once.
import multiprocessing
def square(n: int) -> int:
return n * n
if __name__ == "__main__":
# Pool.map works like map(), but splits the work over 4 processes.
# Results come back in the same order as the input.
with multiprocessing.Pool(processes=4) as pool:
print(pool.map(square, [1, 2, 3, 4, 5])) # [1, 4, 9, 16, 25]
worker = multiprocessing.Process(target=square, args=(7,))
worker.start()
worker.join()
print("exit code:", worker.exitcode) # exit code: 0
Why if __name__ == "__main__": is required
On Windows and macOS, a new process starts a fresh Python that imports your file (this is called spawn). If your file starts processes at the top level, every child starts more children, and you get an error or an endless loop. The guard makes sure only the original program starts processes. Always use it with multiprocessing (on Linux too, so your code works everywhere).
Also:
- The function you send must be defined at the top level of the file (not inside another function or a
lambda), so the child can find it by importing. - Arguments and results are copied between processes (turned into bytes and back, called pickling), so send small data, not huge lists.
- Starting a process takes time. Use processes only for work that takes long enough to be worth it.
Full program: examples/04_gil_and_processes.py (the GIL check, then the same heavy maths sequentially, with threads, and with Pool.map).
Python 3.13.18 | GIL: enabled (version varies)
CPU cores: 4 (varies)
Main process id 3837 (varies)
child process id 3838 says hello (varies)
Sequential 0.73 s (time varies)
Threads 0.84 s (time varies: no faster, because of the GIL)
Processes 0.33 s (time varies: faster, several cores)
Same answers: True
๐ Going deeper: processes don't share variables. To pass data between them use
multiprocessing.Queue, or just return values fromPool.map. In Python 3.14 Linux also stopped using "fork" as the default start method, one more reason to always write the guard.
Read more: the official multiprocessing documentation.
Done here? The practice set for Part 13 โ 8 exercises with solutions โ is on the part page.