blob: 4cc9a9645c49cb5dc4e21b29ba02e69a404578e0 [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
92 .. method:: acquire()
93
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
142 .. method:: wait()
143
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
Larry Hastings3732ed22014-03-15 21:13:56 -0700169 .. method:: 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
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 Stinnerea3183f2013-12-03 01:08:00 +0100216 .. method:: 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
Yury Selivanov37f15bc2014-02-20 16:20:44 -0500228 This method is a :ref:`coroutine <coroutine>`.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100229
230 .. method:: 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
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
261 .. method:: acquire()
262
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
276 .. method:: release()
277
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
313 .. method:: empty()
314
315 Return ``True`` if the queue is empty, ``False`` otherwise.
316
317 .. method:: full()
318
Victor Stinner4f9b7732014-12-22 22:07:06 +0100319 Return ``True`` if there are :attr:`maxsize` items in the queue.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100320
321 .. note::
322
323 If the Queue was initialized with ``maxsize=0`` (the default), then
324 :meth:`full()` is never ``True``.
325
326 .. method:: get()
327
Victor Stinner4f9b7732014-12-22 22:07:06 +0100328 Remove and return an item from the queue. If queue is empty, wait until
329 an item is available.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100330
Yury Selivanov37f15bc2014-02-20 16:20:44 -0500331 This method is a :ref:`coroutine <coroutine>`.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100332
Victor Stinner4f9b7732014-12-22 22:07:06 +0100333 .. seealso::
334
335 The :meth:`empty` method.
336
Victor Stinnerea3183f2013-12-03 01:08:00 +0100337 .. method:: get_nowait()
338
339 Remove and return an item from the queue.
340
341 Return an item if one is immediately available, else raise
Guido van Rossum9ad116b2014-01-25 17:38:31 -0800342 :exc:`QueueEmpty`.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100343
344 .. method:: put(item)
345
Victor Stinner4f9b7732014-12-22 22:07:06 +0100346 Put an item into the queue. If the queue is full, wait until a free slot
347 is available before adding item.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100348
Yury Selivanov37f15bc2014-02-20 16:20:44 -0500349 This method is a :ref:`coroutine <coroutine>`.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100350
Victor Stinner4f9b7732014-12-22 22:07:06 +0100351 .. seealso::
352
353 The :meth:`full` method.
354
Victor Stinnerea3183f2013-12-03 01:08:00 +0100355 .. method:: put_nowait(item)
356
357 Put an item into the queue without blocking.
358
Guido van Rossum9ad116b2014-01-25 17:38:31 -0800359 If no free slot is immediately available, raise :exc:`QueueFull`.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100360
361 .. method:: qsize()
362
363 Number of items in the queue.
364
365 .. attribute:: maxsize
366
367 Number of items allowed in the queue.
368
369
Victor Stinner8c462c52014-01-24 18:11:43 +0100370PriorityQueue
371^^^^^^^^^^^^^
372
Victor Stinnerea3183f2013-12-03 01:08:00 +0100373.. class:: PriorityQueue
374
375 A subclass of :class:`Queue`; retrieves entries in priority order (lowest
376 first).
377
378 Entries are typically tuples of the form: (priority number, data).
379
380
Victor Stinner8c462c52014-01-24 18:11:43 +0100381LifoQueue
382^^^^^^^^^
383
Victor Stinnerea3183f2013-12-03 01:08:00 +0100384.. class:: LifoQueue
385
386 A subclass of :class:`Queue` that retrieves most recently added entries
387 first.
388
389
Victor Stinner8c462c52014-01-24 18:11:43 +0100390JoinableQueue
391^^^^^^^^^^^^^
392
Victor Stinnerea3183f2013-12-03 01:08:00 +0100393.. class:: JoinableQueue
394
395 A subclass of :class:`Queue` with :meth:`task_done` and :meth:`join`
396 methods.
397
398 .. method:: join()
399
400 Block until all items in the queue have been gotten and processed.
401
402 The count of unfinished tasks goes up whenever an item is added to the
403 queue. The count goes down whenever a consumer thread calls
404 :meth:`task_done` to indicate that the item was retrieved and all work on
405 it is complete. When the count of unfinished tasks drops to zero,
406 :meth:`join` unblocks.
407
Yury Selivanov37f15bc2014-02-20 16:20:44 -0500408 This method is a :ref:`coroutine <coroutine>`.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100409
410 .. method:: task_done()
411
412 Indicate that a formerly enqueued task is complete.
413
414 Used by queue consumers. For each :meth:`~Queue.get` used to fetch a task, a
415 subsequent call to :meth:`task_done` tells the queue that the processing
416 on the task is complete.
417
418 If a :meth:`join` is currently blocking, it will resume when all items
419 have been processed (meaning that a :meth:`task_done` call was received
420 for every item that had been :meth:`~Queue.put` into the queue).
421
422 Raises :exc:`ValueError` if called more times than there were items
423 placed in the queue.
424
Guido van Rossum9ad116b2014-01-25 17:38:31 -0800425
426Exceptions
427^^^^^^^^^^
428
429.. exception:: QueueEmpty
430
431 Exception raised when non-blocking :meth:`~Queue.get` (or
432 :meth:`~Queue.get_nowait`) is called
433 on a :class:`Queue` object which is empty.
434
435
436.. exception:: QueueFull
437
438 Exception raised when non-blocking :meth:`~Queue.put` (or
439 :meth:`~Queue.put_nowait`) is called
440 on a :class:`Queue` object which is full.