Sub topic 7
Running Tasks in Separate Processes
This chapter assumes you can write Python functions and scripts, use with statements, and know that the GIL stops two threads from running Python bytecode at the same time. The earlier chapters on threads and the GIL cover that background.
Why a process is different from a thread
A process is a running program with its own memory and its own Python interpreter. Each process in CPython has its own GIL. Two processes can therefore run pure-Python code at the same time on two CPU cores, which threads cannot do on a standard build.
The price is isolation. Processes do not share variables. Anything you send between them must be copied, and starting a process costs far more than starting a thread.
Threads against processes on CPU-bound work
The following program times the same pure-Python countdown with a thread pool and with a process pool. The concurrent.futures pools are covered in a later chapter. Here they only make the comparison short.
import time
from concurrent.futures import ThreadPoolExecutor, ProcessPoolExecutor
def count_down(n):
while n > 0:
n -= 1
def run(executor_cls):
start = time.perf_counter()
with executor_cls(max_workers=4) as pool:
list(pool.map(count_down, [10_000_000] * 4))
return time.perf_counter() - start
if __name__ == "__main__":
print("threads: ", round(run(ThreadPoolExecutor), 2))
print("processes:", round(run(ProcessPoolExecutor), 2))On a standard GIL build with several free cores, the process run is typically faster. The thread run takes about as long as doing the four countdowns one after another. Exact numbers depend on your machine. On a single-core machine, or on a free-threaded build, the gap shrinks or disappears.
Using multiprocessing directly
The multiprocessing module offers a Process class that looks like threading.Thread. You give it a target function and args, call start(), and later call join().
A child cannot return a value the way a function call does, so you pass results back explicitly. A multiprocessing.Queue is one way to do it.
from multiprocessing import Process, Queue
def worker(q):
q.put(sum(range(1_000_000)))
if __name__ == "__main__":
q = Queue()
p = Process(target=worker, args=(q,))
p.start()
print(q.get()) # read the result before joining
p.join()The queue pickles each item, which means Python serializes it to bytes in the child and rebuilds it in the parent. Read from the queue before calling join(). A child that has put a large item on a queue does not exit until that item has been consumed. If the parent joins first, both sides wait for each other forever.
Common errors
- Missing
__main__guard. Under thespawnstart method, each child imports your main module again. Withoutif __name__ == "__main__":around the code that starts processes, you get aRuntimeError, or in older patterns an unwanted chain of new processes. Windows and macOS usespawnby default. - Unpicklable arguments. Lambdas, local functions, open files, and locks cannot be pickled. Define the target function at module top level and pass plain data.
- Expecting shared state. A global that a child modifies is changed only in that child. Return the value through a queue, a pipe, or a pool.
- Tiny tasks. Starting a process and pickling data costs milliseconds or more. If each task runs for less time than that, processes will be slower than a plain loop.
When to reach for processes
Use processes when the work is CPU-bound, written in pure Python, and splits into chunks that are large compared with the cost of copying their inputs and outputs. For work that mostly waits on the network or disk, threads are cheaper and give the same benefit.
Exercise
A script uses four threads to compute hash values for large in-memory lists in pure Python and shows no speedup over one thread. You switch to four processes. Name one reason the speedup may still fall short of 4x.
Show answer
Each task's input and result must be pickled and copied between processes, and each process takes time to start. If the chunks are small, or the machine has fewer than four free cores, these costs and the core limit reduce the gain.