Python Glossary Русский

all Python 3threadingterm

threading.Event

synchronization

A signalling mechanism between threads. One thread sets the flag (set()), the others wait for it (wait()).

Syntax

e = threading.Event()
e.set() / e.clear() / e.wait() / e.is_set()

It replaces busy-waiting on a boolean flag: wait() blocks the thread efficiently, with no spin loop burning CPU. The flag is level-based — after set() it stays raised, and late wait() calls return instantly until someone calls clear(). And wait(timeout) returns the flag's current value (True/False), so a timeout is distinguishable from an actual signal.

Examples

import threading
ready = threading.Event()
import threading
ready = threading.Event()
def producer():
    print('данные готовы')
    ready.set()
def consumer():
    ready.wait()        # блокируется до set()
    print('получил данные')
t1 = threading.Thread(target=producer)
t2 = threading.Thread(target=consumer)
t2.start(); t1.start()
t1.join(); t2.join()

See also

Open in the full glossarydocs.python.orgReport an inaccuracy