On this page
threading.Condition
Prev: threading.BrokenBarrierError | Up: threading | Next: threading.current_thread
Rel: threading.active_count, threading.Barrier, threading.BoundedSemaphore, threading.BrokenBarrierError
Ref: docs.python.org — threading.Condition
Tags: #public #python3 #stdlib #threading
Import
import threading
from threading import Condition
Signature & Overview
threading.Condition(lock=None)
Class that implements a condition variable.
Methods & Attributes
Condition.notify(self, n=1)— Wake up one or more threads waiting on this condition, if any.Condition.notifyAll(self)— Wake up all threads waiting on this condition.Condition.notify_all(self)— Wake up all threads waiting on this condition.Condition.wait(self, timeout=None)— Wait until notified or until a timeout occurs.Condition.wait_for(self, predicate, timeout=None)— Wait until a condition evaluates to True.
Usage
import threading
cond = threading.Condition()
items: list[int] = []
def producer() -> None:
with cond:
items.append(42)
cond.notify()
t = threading.Thread(target=producer)
t.start()
with cond:
assert cond.wait_for(lambda: len(items) > 0, timeout=2)
val = items.pop()
t.join()
assert val == 42
Gotchas
- Always check the predicate in a
whileloop (or usewait_for(predicate)): Spurious wakeups can return fromwait()before the condition is actually true. - Must hold the lock (
with cond:) before callingwait(),notify(), ornotify_all().
REPL Inspect
from threading import Condition
help(Condition)
Linked from
Related notes
- tuts/python3/stdlib_module/threading/active_count Linked here; links to this page; shared tags: #stdlib, #threading
- tuts/python3/stdlib_module/threading/Barrier Linked here; links to this page; shared tags: #stdlib, #threading
- tuts/python3/stdlib_module/threading/BoundedSemaphore Linked here; links to this page; shared tags: #stdlib, #threading
- tuts/python3/stdlib_module/threading/BrokenBarrierError Linked here; links to this page; shared tags: #stdlib, #threading
- tuts/python3/stdlib_module/threading/current_thread Linked here; links to this page; shared tags: #stdlib, #threading
- tuts/python3/stdlib_module/threading Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/threading/enumerate shared tags: #stdlib, #threading
- tuts/python3/stdlib_module/threading/Event shared tags: #stdlib, #threading
- tuts/python3/stdlib_module/threading/excepthook shared tags: #stdlib, #threading
- tuts/python3/stdlib_module/threading/ExceptHookArgs shared tags: #stdlib, #threading