Sub topic 7
Running tasks in separate processes
This chapter assumes you can write Python functions and scripts and use with statements. It also assumes you know why CPU-bound threads are limited by the GIL, as covered in the previous chapter. Here you will learn how a separate process avoids that limit and what it costs.
Why a process helps
A process is a running program with its own memory, its own Python interpreter, and its own GIL. Each interpreter holds its own lock, so two processes never wait on each other's GIL. The operating system can schedule each process on a different CPU core. Pure-Python CPU-bound work then runs in parallel.
The price is isolation. Threads share memory directly. Processes do not, so you must send data between them explicitly.
| Property | Threads | Processes |
|---|---|---|
| Memory | Shared | Separate per process |
| GIL | One, shared by all threads | One per process |
| Pure-Python CPU work in parallel | No (standard build) | Yes |
| Startup cost | Small | Larger (a new interpreter, or a copy of the parent) |
| Passing data | Direct object access | Pickling through a pipe or queue |
| A crash in one worker | Can take down the whole process | Stays in that process |
The Process class
multiprocessing.Process mirrors threading.Thread. You give it a target function and args, call start(), and later call join().
import os
from multiprocessing import Process
def show(label):
print(f"{label}: pid={os.getpid()}, parent={os.getppid()}")
if __name__ == "__main__":
show("main")
p = Process(target=show, args=("child",))
p.start()
p.join()
print("exit code:", p.exitcode)The child reports a different process ID (pid) from the main program. Its parent pid matches the main program's pid. After join(), exitcode is 0 for a normal exit. A negative value -N means the process was killed by signal N.
The if __name__ == "__main__": guard is required for portable code. Under the spawn start method, the child imports your main module again. Without the guard, the child would try to start more children. The start methods chapter covers this in detail. For now, always use the guard.
Memory is not shared
Each process works on its own copy of the data. A global variable changed in a child stays changed only in that child.
from multiprocessing import Process
counter = 0
def bump():
global counter
counter += 1
print("child sees", counter)
if __name__ == "__main__":
p = Process(target=bump)
p.start()
p.join()
print("parent sees", counter)The output is child sees 1 and then parent sees 0. This is the opposite of threads, where all of them would see the same counter.
This isolation removes many race conditions. Two processes cannot corrupt the same Python list, because they never hold the same list. It also means a process cannot hand you a result just by changing a variable. A child must return data through a queue, a pipe, or a pool. Those mechanisms are covered in their own chapters.
The life of a child process
Always call join() on processes you start. A finished child that has not been joined stays in the process table as a zombie until the parent collects it. join() also makes the parent wait, so the program does not move on before the work is done.
Errors in a child
An exception raised in a child does not appear in the parent. The child prints a traceback to standard error and exits with code 1. The parent sees only exitcode == 1. This is a common source of silent failures. Check exitcode after join(), or use a pool, which re-raises worker exceptions in the parent.
Other useful controls:
p.is_alive()tells you whether the child is still running.p.join(timeout=5)waits at most five seconds, then returns. Checkis_alive()afterwards.p.terminate()sends a kill signal. It gives the child no chance to clean up, so locks and temporary files may be left in a bad state.Process(..., daemon=True)creates a process that is terminated when the parent exits normally. A daemon process cannot start children of its own.
Using a pool for many tasks
Starting one Process per task works for a handful of jobs. For many jobs, use a pool. A pool starts a fixed number of worker processes once and feeds them tasks. multiprocessing.Pool is the classic interface. The next chapter covers concurrent.futures, which is usually the better choice in new code.
import time
from multiprocessing import Pool
def count_down(n):
while n > 0:
n -= 1
return n
if __name__ == "__main__":
jobs = [10_000_000] * 4
start = time.perf_counter()
for n in jobs:
count_down(n)
serial = time.perf_counter() - start
start = time.perf_counter()
with Pool(processes=4) as pool:
pool.map(count_down, jobs)
parallel = time.perf_counter() - start
print(f"serial: {serial:.2f}s")
print(f"4 procs: {parallel:.2f}s")On a machine with four or more free cores, the pool run usually takes roughly a quarter to a third of the serial time. Exact numbers depend on your hardware and Python version. Your own measurements matter more than any published figure.
pool.map splits the list into chunks, sends the chunks to workers, and returns results in input order. If a worker raises, map re-raises the exception in the parent. The with block shuts the pool down when it ends.
Choosing the number of workers
For CPU-bound work, more workers than cores does not help. Extra processes just compete for the same cores and use more memory. A reasonable default is the number of cores you are allowed to use:
import os
print("logical CPUs:", os.cpu_count())
print("usable by this process:", len(os.sched_getaffinity(0)))os.sched_getaffinity exists only on some platforms, such as Linux, so it will fail elsewhere. os.cpu_count() ignores container limits and CPU affinity, so inside a container it can report more cores than you can actually use. Python 3.13 adds os.process_cpu_count(), which respects affinity where available.
What processes cost
Parallel speed-up is not free. Three costs decide whether processes pay off.
- Startup. Starting a process takes from a few milliseconds to a few hundred, depending on the start method and how many modules the child imports. A task that runs for one millisecond is slower in a fresh process than in the parent. A pool pays this cost once per worker, not once per task.
- Pickling. Arguments and return values travel between processes as pickled bytes. Large objects take time to serialize, copy, and rebuild. Some objects cannot be pickled at all, such as lambdas, open files, sockets, and locks. A function passed as a target must be importable by name, so define it at module level and not inside another function.
- Memory. Each worker holds its own copy of the data it uses. Four workers processing a 2 GB dataset can need 8 GB if each loads the whole thing.
The practical rule is to send small inputs, do a lot of computation per task, and return small results. A task that sends 100 MB in and does 10 ms of work will spend most of its time on pickling.
Common mistakes
- No
__main__guard. On Windows and macOS, the defaultspawnmethod re-runs your module in each child. Without the guard you get aRuntimeErrorabout starting a new process before the current one has finished bootstrapping. - Expecting shared globals. Changes in a child never reach the parent. Return values explicitly.
- Unpicklable targets. A lambda or a nested function fails with a
PicklingErrororAttributeErrorunderspawn. - Tiny tasks. If each task takes less time than pickling it, the pool is slower than a plain loop. Batch several items into one task, or pass
chunksizetopool.map. - Ignoring
exitcode. A crashed child looks like a normal finish unless you check.
Exercise
A script defines counter = 0 at module level, starts a Process whose target runs counter += 100, and calls join(). The main program then prints counter. What does it print, and why? What are two ways to get the child's result back to the parent?
Show answer
It prints 0. The child runs in its own process with its own copy of memory, so the increment changes only the child's counter. To get the result back, the child can put it on a multiprocessing.Queue (or send it through a Pipe) for the parent to read. Alternatively, run the work through a Pool or ProcessPoolExecutor and use the return value.
Exercise
You run Pool(4).map(f, items) where f takes about 50 microseconds per item and items has 100,000 small integers. The pool version is slower than a plain for loop. Give two reasons, and one change that might help.
Show answer
Each task is so short that the cost of pickling, sending, and receiving it exceeds the work itself, and the pool also pays worker startup. The work per item is too small to benefit from parallelism. Passing a larger chunksize to map sends many items per message and reduces the overhead. Often the best change is to keep the plain loop for work this small.