Python Glossary Русский

Python 3.8+multiprocessingfunction

multiprocessing.parent_process()

processes

Returns the Process object of the current process's parent, or None in the main process. Added in Python 3.8.

Syntax

multiprocessing.parent_process()

This is the most direct answer to "am I the main process?": under spawn the child runs the main module as __mp_main__, which makes __name__ awkward for this, while parent_process() is None is unambiguous. Its pid matches the child's os.getppid(), and is_alive() lets a child notice that its parent died and exit instead of lingering as an orphan.

Examples

import multiprocessing as mp
import os
def check(q):
    parent = mp.parent_process()
    q.put((parent.pid == os.getppid(), __name__))
if __name__ == '__main__':
    print(mp.parent_process())  # → None
    ctx = mp.get_context('spawn')
    q = ctx.Queue()
    p = ctx.Process(target=check, args=(q,))
    p.start()
    print(q.get(timeout=10))  # → (True, '__mp_main__')
    p.join()

See also

Open in the full glossarydocs.python.orgReport an inaccuracy