Name
wait
Synopsis
c
.wait(timeout
=None)
wait
releases L
, then
suspends the calling thread until some other thread calls
notify
or notifyAll
on
c
. The calling thread must hold
L
before it calls
c
.wait( )
.
timeout
is covered earlier in Section 14.4.2.1. After a thread wakes up,
either by notification or timeout, the thread becomes ready when it
acquires L
again. When
wait
returns, the calling thread always holds
L
again.
In typical use, a Condition
object
c
regulates access to some global state
s
that is shared between threads. When a
thread needs to wait for s
to change, the
thread loops as follows:
c
.acquire( ) while not is_ok_state(s
):c
.wait( ) do_some_work_using_state(s
)c
.release( )
Meanwhile, each thread that modifies s
calls notify
(or notifyAll
, if
it needs to wake up all waiting threads, not just one) each time
s
changes:
c
.acquire( ) do_something_that_modifies_state(s
)c
.notify( ) # or,c
.notifyAll( )c
.release( )
As you see, you always need to acquire and release
c
around each use of
c
’s methods, which makes
using Condition
somewhat error-prone.
Get Python in a Nutshell now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.