Python Glossary Русский

all Python 3multiprocessingterm

multiprocessing.Event

synchronization

An event flag shared between processes: set() raises it, wait() waits for it, clear() lowers it. The simplest "go" or "time to stop" signal.

Syntax

ev = ctx.Event(); ev.set(); ev.wait(timeout=None); ev.is_set(); ev.clear()

wait(timeout) does not raise when time runs out; it returns False, so check the result. A common graceful-stop idiom: the child loops while not stop.is_set(), and the parent calls stop.set() and join(), which is safer than terminate() killing the process mid-write. Pass the primitive to the child as a Process argument at creation; it cannot go through a Queue or Pool arguments — RuntimeError "should only be shared between processes through inheritance".

Examples

import multiprocessing as mp
def worker(stop, done):
    while not stop.is_set():
        stop.wait(0.01)
    done.set()
if __name__ == '__main__':
    ctx = mp.get_context('spawn')
    stop, done = ctx.Event(), ctx.Event()
    p = ctx.Process(target=worker, args=(stop, done))
    p.start()
    print(done.wait(0.1))  # → False — таймаут без исключения
    stop.set()
    p.join()
    print(done.is_set(), p.exitcode)  # → True 0

See also

Open in the full glossarydocs.python.orgReport an inaccuracy