• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1.. currentmodule:: asyncio
2.. _asyncio-sync:
3
4Synchronization primitives
5==========================
6
7Locks:
8
9* :class:`Lock`
10* :class:`Event`
11* :class:`Condition`
12
13Semaphores:
14
15* :class:`Semaphore`
16* :class:`BoundedSemaphore`
17
18asyncio lock API was designed to be close to classes of the :mod:`threading`
19module (:class:`~threading.Lock`, :class:`~threading.Event`,
20:class:`~threading.Condition`, :class:`~threading.Semaphore`,
21:class:`~threading.BoundedSemaphore`), but it has no *timeout* parameter. The
22:func:`asyncio.wait_for` function can be used to cancel a task after a timeout.
23
24Locks
25-----
26
27Lock
28^^^^
29
30.. class:: Lock(\*, loop=None)
31
32   Primitive lock objects.
33
34   A primitive lock is a synchronization primitive that is not owned by a
35   particular coroutine when locked.  A primitive lock is in one of two states,
36   'locked' or 'unlocked'.
37
38   It is created in the unlocked state.  It has two basic methods, :meth:`acquire`
39   and :meth:`release`.  When the state is unlocked, acquire() changes the state to
40   locked and returns immediately.  When the state is locked, acquire() blocks
41   until a call to release() in another coroutine changes it to unlocked, then
42   the acquire() call resets it to locked and returns.  The release() method
43   should only be called in the locked state; it changes the state to unlocked
44   and returns immediately.  If an attempt is made to release an unlocked lock,
45   a :exc:`RuntimeError` will be raised.
46
47   When more than one coroutine is blocked in acquire() waiting for the state
48   to turn to unlocked, only one coroutine proceeds when a release() call
49   resets the state to unlocked; first coroutine which is blocked in acquire()
50   is being processed.
51
52   :meth:`acquire` is a coroutine and should be called with ``yield from``.
53
54   Locks also support the context management protocol.  ``(yield from lock)``
55   should be used as the context manager expression.
56
57   This class is :ref:`not thread safe <asyncio-multithreading>`.
58
59   Usage::
60
61       lock = Lock()
62       ...
63       yield from lock
64       try:
65           ...
66       finally:
67           lock.release()
68
69   Context manager usage::
70
71       lock = Lock()
72       ...
73       with (yield from lock):
74           ...
75
76   Lock objects can be tested for locking state::
77
78       if not lock.locked():
79           yield from lock
80       else:
81           # lock is acquired
82           ...
83
84   .. method:: locked()
85
86      Return ``True`` if the lock is acquired.
87
88   .. coroutinemethod:: acquire()
89
90      Acquire a lock.
91
92      This method blocks until the lock is unlocked, then sets it to locked and
93      returns ``True``.
94
95      This method is a :ref:`coroutine <coroutine>`.
96
97   .. method:: release()
98
99      Release a lock.
100
101      When the lock is locked, reset it to unlocked, and return.  If any other
102      coroutines are blocked waiting for the lock to become unlocked, allow
103      exactly one of them to proceed.
104
105      When invoked on an unlocked lock, a :exc:`RuntimeError` is raised.
106
107      There is no return value.
108
109
110Event
111^^^^^
112
113.. class:: Event(\*, loop=None)
114
115   An Event implementation, asynchronous equivalent to :class:`threading.Event`.
116
117   Class implementing event objects. An event manages a flag that can be set to
118   true with the :meth:`set` method and reset to false with the :meth:`clear`
119   method.  The :meth:`wait` method blocks until the flag is true. The flag is
120   initially false.
121
122   This class is :ref:`not thread safe <asyncio-multithreading>`.
123
124   .. method:: clear()
125
126      Reset the internal flag to false. Subsequently, coroutines calling
127      :meth:`wait` will block until :meth:`set` is called to set the internal
128      flag to true again.
129
130   .. method:: is_set()
131
132      Return ``True`` if and only if the internal flag is true.
133
134   .. method:: set()
135
136      Set the internal flag to true. All coroutines waiting for it to become
137      true are awakened. Coroutine that call :meth:`wait` once the flag is true
138      will not block at all.
139
140   .. coroutinemethod:: wait()
141
142      Block until the internal flag is true.
143
144      If the internal flag is true on entry, return ``True`` immediately.
145      Otherwise, block until another coroutine calls :meth:`set` to set the
146      flag to true, then return ``True``.
147
148      This method is a :ref:`coroutine <coroutine>`.
149
150
151Condition
152^^^^^^^^^
153
154.. class:: Condition(lock=None, \*, loop=None)
155
156   A Condition implementation, asynchronous equivalent to
157   :class:`threading.Condition`.
158
159   This class implements condition variable objects. A condition variable
160   allows one or more coroutines to wait until they are notified by another
161   coroutine.
162
163   If the *lock* argument is given and not ``None``, it must be a :class:`Lock`
164   object, and it is used as the underlying lock.  Otherwise,
165   a new :class:`Lock` object is created and used as the underlying lock.
166
167   This class is :ref:`not thread safe <asyncio-multithreading>`.
168
169   .. coroutinemethod:: acquire()
170
171      Acquire the underlying lock.
172
173      This method blocks until the lock is unlocked, then sets it to locked and
174      returns ``True``.
175
176      This method is a :ref:`coroutine <coroutine>`.
177
178   .. method:: notify(n=1)
179
180      By default, wake up one coroutine waiting on this condition, if any.
181      If the calling coroutine has not acquired the lock when this method is
182      called, a :exc:`RuntimeError` is raised.
183
184      This method wakes up at most *n* of the coroutines waiting for the
185      condition variable; it is a no-op if no coroutines are waiting.
186
187      .. note::
188
189         An awakened coroutine does not actually return from its :meth:`wait`
190         call until it can reacquire the lock. Since :meth:`notify` does not
191         release the lock, its caller should.
192
193   .. method:: locked()
194
195      Return ``True`` if the underlying lock is acquired.
196
197   .. method:: notify_all()
198
199      Wake up all coroutines waiting on this condition. This method acts like
200      :meth:`notify`, but wakes up all waiting coroutines instead of one. If the
201      calling coroutine has not acquired the lock when this method is called, a
202      :exc:`RuntimeError` is raised.
203
204   .. method:: release()
205
206      Release the underlying lock.
207
208      When the lock is locked, reset it to unlocked, and return. If any other
209      coroutines are blocked waiting for the lock to become unlocked, allow
210      exactly one of them to proceed.
211
212      When invoked on an unlocked lock, a :exc:`RuntimeError` is raised.
213
214      There is no return value.
215
216   .. coroutinemethod:: wait()
217
218      Wait until notified.
219
220      If the calling coroutine has not acquired the lock when this method is
221      called, a :exc:`RuntimeError` is raised.
222
223      This method releases the underlying lock, and then blocks until it is
224      awakened by a :meth:`notify` or :meth:`notify_all` call for the same
225      condition variable in another coroutine.  Once awakened, it re-acquires
226      the lock and returns ``True``.
227
228      This method is a :ref:`coroutine <coroutine>`.
229
230   .. coroutinemethod:: wait_for(predicate)
231
232      Wait until a predicate becomes true.
233
234      The predicate should be a callable which result will be interpreted as a
235      boolean value. The final predicate value is the return value.
236
237      This method is a :ref:`coroutine <coroutine>`.
238
239
240Semaphores
241----------
242
243Semaphore
244^^^^^^^^^
245
246.. class:: Semaphore(value=1, \*, loop=None)
247
248   A Semaphore implementation.
249
250   A semaphore manages an internal counter which is decremented by each
251   :meth:`acquire` call and incremented by each :meth:`release` call. The
252   counter can never go below zero; when :meth:`acquire` finds that it is zero,
253   it blocks, waiting until some other coroutine calls :meth:`release`.
254
255   Semaphores also support the context management protocol.
256
257   The optional argument gives the initial value for the internal counter; it
258   defaults to ``1``. If the value given is less than ``0``, :exc:`ValueError`
259   is raised.
260
261   This class is :ref:`not thread safe <asyncio-multithreading>`.
262
263   .. coroutinemethod:: acquire()
264
265      Acquire a semaphore.
266
267      If the internal counter is larger than zero on entry, decrement it by one
268      and return ``True`` immediately.  If it is zero on entry, block, waiting
269      until some other coroutine has called :meth:`release` to make it larger
270      than ``0``, and then return ``True``.
271
272      This method is a :ref:`coroutine <coroutine>`.
273
274   .. method:: locked()
275
276      Returns ``True`` if semaphore can not be acquired immediately.
277
278   .. method:: release()
279
280      Release a semaphore, incrementing the internal counter by one. When it
281      was zero on entry and another coroutine is waiting for it to become
282      larger than zero again, wake up that coroutine.
283
284
285BoundedSemaphore
286^^^^^^^^^^^^^^^^
287
288.. class:: BoundedSemaphore(value=1, \*, loop=None)
289
290   A bounded semaphore implementation. Inherit from :class:`Semaphore`.
291
292   This raises :exc:`ValueError` in :meth:`~Semaphore.release` if it would
293   increase the value above the initial value.
294