On this page
multiprocessing
Prev: msvcrt | Up: stdlib_module | Next: netrc
Rel: os, io, time, argparse, getopt
Ref: docs.python.org — multiprocessing
Tags: #public #python3 #stdlib
Import
import multiprocessing
Overview
Spawns separate OS Python processes to achieve true multi-core parallelism for CPU-bound Python code (bypassing the GIL), with IPC primitives (Queue, Pipe, Value, Array, shared_memory) and worker pools (Pool). For simple map/submit workflows prefer concurrent.futures.ProcessPoolExecutor; for I/O-bound work prefer asyncio or threading.
Quick Start
import multiprocessing as mp
def square(n: int) -> int:
return n * n
if __name__ == "__main__":
with mp.Pool(processes=2) as pool:
assert pool.map(square, [1, 2, 3, 4]) == [1, 4, 9, 16]
Implementation Walkthrough
1. Explicit Context (get_context("spawn")) & Producer/Consumer Queue
Using an explicit start method ("spawn" or "forkserver") keeps behavior consistent across macOS, Windows, and Linux and avoids deadlocks from inheriting multithreaded locks:
import multiprocessing as mp
def worker(q: mp.Queue) -> None:
q.put({"status": "ok"})
if __name__ == "__main__":
ctx = mp.get_context("spawn")
q = ctx.Queue()
proc = ctx.Process(target=worker, args=(q,))
proc.start()
result = q.get(timeout=5)
proc.join()
assert result == {"status": "ok"}
2. Zero-Copy Buffers via multiprocessing.shared_memory
For large byte buffers or arrays, pass a SharedMemory name instead of pickling megabytes over a Queue.
Gotchas & Boundaries
- Always guard entry points with
if __name__ == "__main__":: Without it,"spawn"(the default on macOS and Windows) recursively re-imports and spawns infinite processes. - Arguments and return values must be picklable: Top-level functions and dataclasses work; lambdas, closures, and open file handles raise
PicklingError. - Avoid
"fork"in multithreaded programs: Forking after starting threads can deadlock on inherited locks. - Process startup is expensive: Batch small items (
chunksize=inPool.map) so IPC overhead doesn't dwarf the actual computation.
Common Functions
- multiprocessing.active_children() —
active_children()— Return list of process objects corresponding to live child processes - multiprocessing.allow_connection_pickling() —
allow_connection_pickling()— Install support for sending connections and sockets between processes - multiprocessing.Array() —
Array(typecode_or_type, size_or_initializer, *, lock=True)— Returns a synchronized shared array - multiprocessing.Barrier() —
Barrier(parties, action=None, timeout=None)— Returns a barrier object - multiprocessing.BoundedSemaphore() —
BoundedSemaphore(value=1)— Returns a bounded semaphore object - multiprocessing.Condition() —
Condition(lock=None)— Returns a condition object - multiprocessing.cpu_count() —
cpu_count()— Returns the number of CPUs in the system - multiprocessing.current_process() —
current_process()— Return process object representing the current process - multiprocessing.Event() —
Event()— Returns an event object - multiprocessing.freeze_support() —
freeze_support()— Check whether this is a fake forked process in a frozen executable. - multiprocessing.get_all_start_methods() —
get_all_start_methods()— Returns a list of the supported start methods, default first. - multiprocessing.get_context() —
get_context(method=None)—multiprocessing.get_context()function. - multiprocessing.get_logger() —
get_logger()— Return package logger -- if it does not already exist then it is created. - multiprocessing.get_start_method() —
get_start_method(allow_none=False)—multiprocessing.get_start_method()function. - multiprocessing.JoinableQueue() —
JoinableQueue(maxsize=0)— Returns a queue object - multiprocessing.Lock() —
Lock()— Returns a non-recursive lock object - multiprocessing.log_to_stderr() —
log_to_stderr(level=None)— Turn on logging and add a handler which prints to stderr - multiprocessing.Manager() —
Manager()— Returns a manager associated with a running server process The managers methods such asLock(),Condition()andQueue()can be used to create shared objects. - multiprocessing.parent_process() —
parent_process()— Return process object representing the parent process - multiprocessing.Pipe() —
Pipe(duplex=True)— Returns two connection object connected by a pipe - multiprocessing.Pool() —
Pool(processes=None, initializer=None, initargs=(), maxtasksperchild=None)— Returns a process pool object - multiprocessing.Queue() —
Queue(maxsize=0)— Returns a queue object - multiprocessing.RawArray() —
RawArray(typecode_or_type, size_or_initializer)— Returns a shared array - multiprocessing.RawValue() —
RawValue(typecode_or_type, *args)— Returns a shared object - multiprocessing.RLock() —
RLock()— Returns a recursive lock object - multiprocessing.Semaphore() —
Semaphore(value=1)— Returns a semaphore object - multiprocessing.set_executable() —
set_executable(executable)— Sets the path to a python.exe or pythonw.exe binary used to run child processes instead of sys.executable when using the 'spawn' start method. Useful for people embedding Python. - multiprocessing.set_forkserver_preload() —
set_forkserver_preload(module_names)— Set list of module names to try to load in forkserver process. - multiprocessing.set_start_method() —
set_start_method(method, force=False)—multiprocessing.set_start_method()function. - multiprocessing.SimpleQueue() —
SimpleQueue()— Returns a queue object - multiprocessing.Value() —
Value(typecode_or_type, *args, lock=True)— Returns a synchronized shared object
Classes & Objects
- multiprocessing.AuthenticationError —
multiprocessing.AuthenticationErrorclass. (Methods:.add_note(),.with_traceback()) - multiprocessing.BufferTooShort —
multiprocessing.BufferTooShortclass. (Methods:.add_note(),.with_traceback()) - multiprocessing.Process —
multiprocessing.Processclass. (Methods:.authkey(),.close(),.daemon(),.exitcode(),.ident(),.interrupt()) - multiprocessing.ProcessError —
multiprocessing.ProcessErrorclass. (Methods:.add_note(),.with_traceback()) - multiprocessing.TimeoutError —
multiprocessing.TimeoutErrorclass. (Methods:.add_note(),.with_traceback())
Linked from
- tuts/python3
- tuts/python3/stdlib_module
- tuts/python3/stdlib_module/concurrent
- tuts/python3/stdlib_module/msvcrt
- tuts/python3/stdlib_module/multiprocessing/active_children
- tuts/python3/stdlib_module/multiprocessing/allow_connection_pickling
- tuts/python3/stdlib_module/multiprocessing/Array
- tuts/python3/stdlib_module/multiprocessing/AuthenticationError
- tuts/python3/stdlib_module/multiprocessing/Barrier
- tuts/python3/stdlib_module/multiprocessing/BoundedSemaphore
- tuts/python3/stdlib_module/multiprocessing/BufferTooShort
- tuts/python3/stdlib_module/multiprocessing/Condition
- tuts/python3/stdlib_module/multiprocessing/cpu_count
- tuts/python3/stdlib_module/multiprocessing/current_process
- tuts/python3/stdlib_module/multiprocessing/Event
- tuts/python3/stdlib_module/multiprocessing/freeze_support
- tuts/python3/stdlib_module/multiprocessing/get_all_start_methods
- tuts/python3/stdlib_module/multiprocessing/get_context
- tuts/python3/stdlib_module/multiprocessing/get_logger
- tuts/python3/stdlib_module/multiprocessing/get_start_method
- tuts/python3/stdlib_module/multiprocessing/JoinableQueue
- tuts/python3/stdlib_module/multiprocessing/Lock
- tuts/python3/stdlib_module/multiprocessing/log_to_stderr
- tuts/python3/stdlib_module/multiprocessing/Manager
- tuts/python3/stdlib_module/multiprocessing/parent_process
- tuts/python3/stdlib_module/multiprocessing/Pipe
- tuts/python3/stdlib_module/multiprocessing/Pool
- tuts/python3/stdlib_module/multiprocessing/Process
- tuts/python3/stdlib_module/multiprocessing/ProcessError
- tuts/python3/stdlib_module/multiprocessing/Queue
- tuts/python3/stdlib_module/multiprocessing/RawArray
- tuts/python3/stdlib_module/multiprocessing/RawValue
- tuts/python3/stdlib_module/multiprocessing/RLock
- tuts/python3/stdlib_module/multiprocessing/Semaphore
- tuts/python3/stdlib_module/multiprocessing/set_executable
- tuts/python3/stdlib_module/multiprocessing/set_forkserver_preload
- tuts/python3/stdlib_module/multiprocessing/set_start_method
- tuts/python3/stdlib_module/multiprocessing/SimpleQueue
- tuts/python3/stdlib_module/multiprocessing/TimeoutError
- tuts/python3/stdlib_module/multiprocessing/Value
- tuts/python3/stdlib_module/netrc
- tuts/python3/stdlib_module/stdlib_module
- tuts/python3/tutorials/advanced_python_internals/concurrency_and_parallelism
Related notes
- tuts/python3/stdlib_module/msvcrt Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/multiprocessing/active_children Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/multiprocessing/allow_connection_pickling Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/multiprocessing/Array Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/multiprocessing/AuthenticationError Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/multiprocessing/Barrier Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/multiprocessing/BoundedSemaphore Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/multiprocessing/BufferTooShort Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/multiprocessing/Condition Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/multiprocessing/cpu_count Linked here; links to this page; shared tags: #stdlib