blob: e3d82b0dc4b4873fd77330ecade01f334818c900 [file] [log] [blame]
R David Murray6a143812013-12-20 14:37:39 -05001.. currentmodule:: asyncio
Victor Stinner606ab032014-02-01 03:18:58 +01002.. _asyncio-sync:
Victor Stinnerea3183f2013-12-03 01:08:00 +01003
4Synchronization primitives
5==========================
6
Victor Stinner7a55b882015-01-30 00:37:04 +01007Locks:
8
9* :class:`Lock`
10* :class:`Event`
11* :class:`Condition`
12* :class:`Semaphore`
13* :class:`BoundedSemaphore`
14
15Queues:
16
17* :class:`Queue`
18* :class:`PriorityQueue`
19* :class:`LifoQueue`
20* :class:`JoinableQueue`
21
22asyncio locks and queues API were designed to be close to classes of the
23:mod:`threading` module (:class:`~threading.Lock`, :class:`~threading.Event`,
24:class:`~threading.Condition`, :class:`~threading.Semaphore`,
25:class:`~threading.BoundedSemaphore`) and the :mod:`queue` module
26(:class:`~queue.Queue`, :class:`~queue.PriorityQueue`,
27:class:`~queue.LifoQueue`), but they have no *timeout* parameter. The
28:func:`asyncio.wait_for` function can be used to cancel a task after a timeout.
29
Victor Stinnerea3183f2013-12-03 01:08:00 +010030Locks
31-----
32
Victor Stinner8c462c52014-01-24 18:11:43 +010033Lock
34^^^^
35
Victor Stinnerea3183f2013-12-03 01:08:00 +010036.. class:: Lock(\*, loop=None)
37
38 Primitive lock objects.
39
40 A primitive lock is a synchronization primitive that is not owned by a
41 particular coroutine when locked. A primitive lock is in one of two states,
42 'locked' or 'unlocked'.
43
44 It is created in the unlocked state. It has two basic methods, :meth:`acquire`
45 and :meth:`release`. When the state is unlocked, acquire() changes the state to
46 locked and returns immediately. When the state is locked, acquire() blocks
47 until a call to release() in another coroutine changes it to unlocked, then
48 the acquire() call resets it to locked and returns. The release() method
49 should only be called in the locked state; it changes the state to unlocked
50 and returns immediately. If an attempt is made to release an unlocked lock,
51 a :exc:`RuntimeError` will be raised.
52
53 When more than one coroutine is blocked in acquire() waiting for the state
54 to turn to unlocked, only one coroutine proceeds when a release() call
55 resets the state to unlocked; first coroutine which is blocked in acquire()
56 is being processed.
57
58 :meth:`acquire` is a coroutine and should be called with ``yield from``.
59
Serhiy Storchaka14867992014-09-10 23:43:41 +030060 Locks also support the context management protocol. ``(yield from lock)``
Victor Stinnerea3183f2013-12-03 01:08:00 +010061 should be used as context manager expression.
62
63 Usage::
64
65 lock = Lock()
66 ...
67 yield from lock
68 try:
69 ...
70 finally:
71 lock.release()
72
73 Context manager usage::
74
75 lock = Lock()
76 ...
77 with (yield from lock):
78 ...
79
80 Lock objects can be tested for locking state::
81
82 if not lock.locked():
83 yield from lock
84 else:
85 # lock is acquired
86 ...
87
88 .. method:: locked()
89
Larry Hastings3732ed22014-03-15 21:13:56 -070090 Return ``True`` if the lock is acquired.
Victor Stinnerea3183f2013-12-03 01:08:00 +010091
Victor Stinnerbdd574d2015-02-12 22:49:18 +010092 .. coroutinemethod:: acquire()
Victor Stinnerea3183f2013-12-03 01:08:00 +010093
94 Acquire a lock.
95
96 This method blocks until the lock is unlocked, then sets it to locked and
97 returns ``True``.
98
Larry Hastings3732ed22014-03-15 21:13:56 -070099 This method is a :ref:`coroutine <coroutine>`.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100100
101 .. method:: release()
102
103 Release a lock.
104
105 When the lock is locked, reset it to unlocked, and return. If any other
106 coroutines are blocked waiting for the lock to become unlocked, allow
107 exactly one of them to proceed.
108
109 When invoked on an unlocked lock, a :exc:`RuntimeError` is raised.
110
111 There is no return value.
112
113
Victor Stinner8c462c52014-01-24 18:11:43 +0100114Event
115^^^^^
116
Victor Stinnerea3183f2013-12-03 01:08:00 +0100117.. class:: Event(\*, loop=None)
118
119 An Event implementation, asynchronous equivalent to :class:`threading.Event`.
120
121 Class implementing event objects. An event manages a flag that can be set to
122 true with the :meth:`set` method and reset to false with the :meth:`clear`
123 method. The :meth:`wait` method blocks until the flag is true. The flag is
124 initially false.
125
126 .. method:: clear()
127
128 Reset the internal flag to false. Subsequently, coroutines calling
129 :meth:`wait` will block until :meth:`set` is called to set the internal
130 flag to true again.
131
132 .. method:: is_set()
133
134 Return ``True`` if and only if the internal flag is true.
135
136 .. method:: set()
137
138 Set the internal flag to true. All coroutines waiting for it to become
139 true are awakened. Coroutine that call :meth:`wait` once the flag is true
140 will not block at all.
141
Victor Stinnerbdd574d2015-02-12 22:49:18 +0100142 .. coroutinemethod:: wait()
Victor Stinnerea3183f2013-12-03 01:08:00 +0100143
144 Block until the internal flag is true.
145
146 If the internal flag is true on entry, return ``True`` immediately.
147 Otherwise, block until another coroutine calls :meth:`set` to set the
148 flag to true, then return ``True``.
149
Yury Selivanov37f15bc2014-02-20 16:20:44 -0500150 This method is a :ref:`coroutine <coroutine>`.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100151
152
Victor Stinner8c462c52014-01-24 18:11:43 +0100153Condition
154^^^^^^^^^
155
Andrew Svetlovf200ce62014-07-26 19:50:37 +0300156.. class:: Condition(lock=None, \*, loop=None)
Victor Stinnerea3183f2013-12-03 01:08:00 +0100157
158 A Condition implementation, asynchronous equivalent to
159 :class:`threading.Condition`.
160
161 This class implements condition variable objects. A condition variable
162 allows one or more coroutines to wait until they are notified by another
163 coroutine.
164
Andrew Svetlovf200ce62014-07-26 19:50:37 +0300165 If the *lock* argument is given and not ``None``, it must be a :class:`Lock`
166 object, and it is used as the underlying lock. Otherwise,
167 a new :class:`Lock` object is created and used as the underlying lock.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100168
Victor Stinnerbdd574d2015-02-12 22:49:18 +0100169 .. coroutinemethod:: acquire()
Larry Hastings3732ed22014-03-15 21:13:56 -0700170
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
Victor Stinnerea3183f2013-12-03 01:08:00 +0100178 .. 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
Larry Hastings3732ed22014-03-15 21:13:56 -0700193 .. method:: locked()
194
195 Return ``True`` if the underlying lock is acquired.
196
Victor Stinnerea3183f2013-12-03 01:08:00 +0100197 .. method:: notify_all()
198
199 Wake up all threads waiting on this condition. This method acts like
200 :meth:`notify`, but wakes up all waiting threads instead of one. If the
201 calling thread has not acquired the lock when this method is called, a
202 :exc:`RuntimeError` is raised.
203
Larry Hastings3732ed22014-03-15 21:13:56 -0700204 .. 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
Victor Stinnerbdd574d2015-02-12 22:49:18 +0100216 .. coroutinemethod:: wait()
Victor Stinnerea3183f2013-12-03 01:08:00 +0100217
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
Yury Selivanov37f15bc2014-02-20 16:20:44 -0500228 This method is a :ref:`coroutine <coroutine>`.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100229
Victor Stinnerbdd574d2015-02-12 22:49:18 +0100230 .. coroutinemethod:: wait_for(predicate)
Victor Stinnerea3183f2013-12-03 01:08:00 +0100231
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
Yury Selivanov37f15bc2014-02-20 16:20:44 -0500237 This method is a :ref:`coroutine <coroutine>`.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100238
239
240Semaphores
241----------
242
Victor Stinner8c462c52014-01-24 18:11:43 +0100243Semaphore
244^^^^^^^^^
245
Victor Stinnerea3183f2013-12-03 01:08:00 +0100246.. 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 thread calls :meth:`release`.
254
Serhiy Storchaka14867992014-09-10 23:43:41 +0300255 Semaphores also support the context management protocol.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100256
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
Victor Stinnerbdd574d2015-02-12 22:49:18 +0100261 .. coroutinemethod:: acquire()
Victor Stinnerea3183f2013-12-03 01:08:00 +0100262
263 Acquire a semaphore.
264
265 If the internal counter is larger than zero on entry, decrement it by one
266 and return ``True`` immediately. If it is zero on entry, block, waiting
267 until some other coroutine has called :meth:`release` to make it larger
268 than ``0``, and then return ``True``.
269
Yury Selivanov37f15bc2014-02-20 16:20:44 -0500270 This method is a :ref:`coroutine <coroutine>`.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100271
272 .. method:: locked()
273
274 Returns ``True`` if semaphore can not be acquired immediately.
275
Victor Stinnerbdd574d2015-02-12 22:49:18 +0100276 .. coroutinemethod:: release()
Victor Stinnerea3183f2013-12-03 01:08:00 +0100277
278 Release a semaphore, incrementing the internal counter by one. When it
279 was zero on entry and another coroutine is waiting for it to become
280 larger than zero again, wake up that coroutine.
281
282
Victor Stinner8c462c52014-01-24 18:11:43 +0100283BoundedSemaphore
284^^^^^^^^^^^^^^^^
285
Victor Stinnerea3183f2013-12-03 01:08:00 +0100286.. class:: BoundedSemaphore(value=1, \*, loop=None)
287
288 A bounded semaphore implementation. Inherit from :class:`Semaphore`.
289
290 This raises :exc:`ValueError` in :meth:`~Semaphore.release` if it would
291 increase the value above the initial value.
292
293
294Queues
295------
296
Victor Stinner8c462c52014-01-24 18:11:43 +0100297Queue
298^^^^^
299
Victor Stinnerea3183f2013-12-03 01:08:00 +0100300.. class:: Queue(maxsize=0, \*, loop=None)
301
302 A queue, useful for coordinating producer and consumer coroutines.
303
304 If *maxsize* is less than or equal to zero, the queue size is infinite. If
305 it is an integer greater than ``0``, then ``yield from put()`` will block
306 when the queue reaches *maxsize*, until an item is removed by :meth:`get`.
307
308 Unlike the standard library :mod:`queue`, you can reliably know this Queue's
Victor Stinner2748bc72013-12-13 10:57:04 +0100309 size with :meth:`qsize`, since your single-threaded asyncio application won't
Victor Stinnerea3183f2013-12-03 01:08:00 +0100310 be interrupted between calling :meth:`qsize` and doing an operation on the
311 Queue.
312
Victor Stinnerf91d8452015-02-17 23:09:52 +0100313 .. versionchanged:: 3.4.3
314 New :meth:`join` and :meth:`task_done` methods.
315
Victor Stinnerea3183f2013-12-03 01:08:00 +0100316 .. method:: empty()
317
318 Return ``True`` if the queue is empty, ``False`` otherwise.
319
320 .. method:: full()
321
Victor Stinner4f9b7732014-12-22 22:07:06 +0100322 Return ``True`` if there are :attr:`maxsize` items in the queue.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100323
324 .. note::
325
326 If the Queue was initialized with ``maxsize=0`` (the default), then
327 :meth:`full()` is never ``True``.
328
Victor Stinnerbdd574d2015-02-12 22:49:18 +0100329 .. coroutinemethod:: get()
Victor Stinnerea3183f2013-12-03 01:08:00 +0100330
Victor Stinner4f9b7732014-12-22 22:07:06 +0100331 Remove and return an item from the queue. If queue is empty, wait until
332 an item is available.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100333
Yury Selivanov37f15bc2014-02-20 16:20:44 -0500334 This method is a :ref:`coroutine <coroutine>`.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100335
Victor Stinner4f9b7732014-12-22 22:07:06 +0100336 .. seealso::
337
338 The :meth:`empty` method.
339
Victor Stinnerea3183f2013-12-03 01:08:00 +0100340 .. method:: get_nowait()
341
342 Remove and return an item from the queue.
343
344 Return an item if one is immediately available, else raise
Guido van Rossum9ad116b2014-01-25 17:38:31 -0800345 :exc:`QueueEmpty`.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100346
Victor Stinnerf91d8452015-02-17 23:09:52 +0100347 .. coroutinemethod:: join()
348
349 Block until all items in the queue have been gotten and processed.
350
351 The count of unfinished tasks goes up whenever an item is added to the
352 queue. The count goes down whenever a consumer thread calls
353 :meth:`task_done` to indicate that the item was retrieved and all work on
354 it is complete. When the count of unfinished tasks drops to zero,
355 :meth:`join` unblocks.
356
357 This method is a :ref:`coroutine <coroutine>`.
358
359 .. versionadded:: 3.4.3
360
Victor Stinnerbdd574d2015-02-12 22:49:18 +0100361 .. coroutinemethod:: put(item)
Victor Stinnerea3183f2013-12-03 01:08:00 +0100362
Victor Stinner4f9b7732014-12-22 22:07:06 +0100363 Put an item into the queue. If the queue is full, wait until a free slot
364 is available before adding item.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100365
Yury Selivanov37f15bc2014-02-20 16:20:44 -0500366 This method is a :ref:`coroutine <coroutine>`.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100367
Victor Stinner4f9b7732014-12-22 22:07:06 +0100368 .. seealso::
369
370 The :meth:`full` method.
371
Victor Stinnerea3183f2013-12-03 01:08:00 +0100372 .. method:: put_nowait(item)
373
374 Put an item into the queue without blocking.
375
Guido van Rossum9ad116b2014-01-25 17:38:31 -0800376 If no free slot is immediately available, raise :exc:`QueueFull`.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100377
378 .. method:: qsize()
379
380 Number of items in the queue.
381
Victor Stinnerf91d8452015-02-17 23:09:52 +0100382 .. method:: task_done()
383
384 Indicate that a formerly enqueued task is complete.
385
386 Used by queue consumers. For each :meth:`~Queue.get` used to fetch a task, a
387 subsequent call to :meth:`task_done` tells the queue that the processing
388 on the task is complete.
389
390 If a :meth:`join` is currently blocking, it will resume when all items
391 have been processed (meaning that a :meth:`task_done` call was received
392 for every item that had been :meth:`~Queue.put` into the queue).
393
394 Raises :exc:`ValueError` if called more times than there were items
395 placed in the queue.
396
397 .. versionadded:: 3.4.3
398
Victor Stinnerea3183f2013-12-03 01:08:00 +0100399 .. attribute:: maxsize
400
401 Number of items allowed in the queue.
402
403
Victor Stinner8c462c52014-01-24 18:11:43 +0100404PriorityQueue
405^^^^^^^^^^^^^
406
Victor Stinnerea3183f2013-12-03 01:08:00 +0100407.. class:: PriorityQueue
408
409 A subclass of :class:`Queue`; retrieves entries in priority order (lowest
410 first).
411
412 Entries are typically tuples of the form: (priority number, data).
413
414
Victor Stinner8c462c52014-01-24 18:11:43 +0100415LifoQueue
416^^^^^^^^^
417
Victor Stinnerea3183f2013-12-03 01:08:00 +0100418.. class:: LifoQueue
419
420 A subclass of :class:`Queue` that retrieves most recently added entries
421 first.
422
423
Victor Stinner8c462c52014-01-24 18:11:43 +0100424JoinableQueue
425^^^^^^^^^^^^^
426
Victor Stinnerea3183f2013-12-03 01:08:00 +0100427.. class:: JoinableQueue
428
Victor Stinnerf91d8452015-02-17 23:09:52 +0100429 Deprecated alias for :class:`Queue`.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100430
Victor Stinnerf91d8452015-02-17 23:09:52 +0100431 .. deprecated:: 3.4.3
Victor Stinnerea3183f2013-12-03 01:08:00 +0100432
Guido van Rossum9ad116b2014-01-25 17:38:31 -0800433
434Exceptions
435^^^^^^^^^^
436
437.. exception:: QueueEmpty
438
Victor Stinner17d87f82015-02-03 15:09:24 +0100439 Exception raised when the :meth:`~Queue.get_nowait` method is called on a
440 :class:`Queue` object which is empty.
Guido van Rossum9ad116b2014-01-25 17:38:31 -0800441
442
443.. exception:: QueueFull
444
Victor Stinner17d87f82015-02-03 15:09:24 +0100445 Exception raised when the :meth:`~Queue.put_nowait` method is called on a
446 :class:`Queue` object which is full.