Python Glossary Русский

all Python 3multiprocessingfunction

multiprocessing.current_process()

processes

Returns the Process object of the current process: MainProcess in the main one, the child's own Process with its name and pid inside a child. The analogue of threading.current_thread().

Syntax

multiprocessing.current_process()

The child's name is set in the parent (name=...) and travels to the child with the object under spawn, which helps in logs. Pool workers are named like SpawnPoolWorker-1 or ForkPoolWorker-1, so the name reveals the start method. Telling the main process apart by the name 'MainProcess' is fragile; parent_process() is None is more reliable. In the main process current_process() has its own pid and exitcode None, since the process is still running.

Examples

import multiprocessing as mp
def report(q):
    q.put(mp.current_process().name)
if __name__ == '__main__':
    print(mp.current_process().name)  # → MainProcess
    ctx = mp.get_context('spawn')
    q = ctx.Queue()
    p = ctx.Process(target=report, args=(q,), name='worker-1')
    p.start()
    print(q.get(timeout=10))  # → worker-1
    p.join()
import multiprocessing as mp
def name(_):
    return mp.current_process().name
if __name__ == '__main__':
    with mp.get_context('spawn').Pool(1) as pool:
        print(pool.map(name, [0])[0].startswith('SpawnPoolWorker'))  # → True

See also

Open in the full glossarydocs.python.orgReport an inaccuracy