Python Glossary Русский

all Python 3multiprocessingterm

multiprocessing.Process

processes

A separate OS process with its own interpreter and memory: target runs there after start(), join() waits for it. It sidesteps the GIL for CPU-bound work.

Syntax

p = ctx.Process(target=func, args=(...), kwargs={}, name=None, daemon=None); p.start(); p.join(timeout=None)

Keep the launching code under if __name__ == '__main__': with spawn (Windows, macOS) and forkserver (Linux since 3.14) the child re-imports the main module, and without the guard it would start spawning processes itself, ending in RuntimeError. target and args travel through pickle, so lambdas and nested functions will not do; use top-level module functions. Memory is not shared: a global changed in the child stays unchanged in the parent. An exception in the child never reaches the parent; you only get a traceback on stderr and exitcode 1, so check it after join().

Examples

import multiprocessing as mp
counter = 0
def work(n):
    global counter
    counter += n
    print('child counter', counter)  # → child counter 5
if __name__ == '__main__':
    ctx = mp.get_context('spawn')
    p = ctx.Process(target=work, args=(5,))
    p.start()
    p.join()
    print(p.exitcode, counter)  # → 0 0 — у родителя своя копия переменной
import multiprocessing as mp
if __name__ == '__main__':
    ctx = mp.get_context('spawn')
    p = ctx.Process(target=int, args=('oops',))  # ValueError в ребёнке
    p.start()
    p.join()
    print('parent still alive, exitcode', p.exitcode)  # → parent still alive, exitcode 1
import multiprocessing as mp
if __name__ == '__main__':
    ctx = mp.get_context('spawn')
    p = ctx.Process(target=lambda: print('hi'))
    try:
        p.start()
    except Exception as e:
        print('lambda cannot be pickled:', type(e).__name__)  # → lambda cannot be pickled: PicklingError

See also

Open in the full glossarydocs.python.orgReport an inaccuracy