Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 19 additions & 0 deletions Doc/library/asyncio-queue.rst
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,15 @@ Queue
If the queue was initialized with ``maxsize=0`` (the default),
then :meth:`full` never returns ``True``.

A slot freed while :meth:`put` calls are waiting is reserved
for the first of them until it resumes, so :meth:`full` can return
``True`` while :meth:`qsize` is less than :attr:`maxsize`, or even
while :meth:`empty` returns ``True``. In that case :meth:`put_nowait`
raises :exc:`QueueFull` even right after :meth:`get_nowait`.

.. versionchanged:: next
Slots reserved for waiting :meth:`put` calls are counted as full.

.. method:: get()
:async:

Expand Down Expand Up @@ -90,6 +99,16 @@ Queue
Put an item into the queue. If the queue is full, wait until a
free slot is available before adding the item.

Waiting calls are served in first in, first out order: a slot freed
while calls are waiting is reserved for the first of them and cannot
be taken by a later :meth:`put` or :meth:`put_nowait`.
A call made while earlier calls were woken up but have not run yet
waits behind them, even if the queue is not full, but
:meth:`put_nowait` can still take other free slots.

.. versionchanged:: next
A freed slot is reserved for the longest waiting call.

Raises :exc:`QueueShutDown` if the queue has been shut down.

.. method:: put_nowait(item)
Expand Down
13 changes: 13 additions & 0 deletions Doc/whatsnew/3.16.rst
Original file line number Diff line number Diff line change
Expand Up @@ -1446,6 +1446,19 @@ Porting to Python 3.16
This section lists previously described changes and other bugfixes
that may require changes to your code.

* :meth:`asyncio.Queue.get` and :meth:`asyncio.Queue.get_nowait` now reserve
the freed slot for the longest waiting :meth:`asyncio.Queue.put` call, and
:meth:`asyncio.Queue.full` counts reserved slots. ``full()`` can therefore
return ``True`` while :meth:`~asyncio.Queue.qsize` is less than
:attr:`~asyncio.Queue.maxsize` or ``empty()`` is ``True``, and ``put()`` can
wait while ``full()`` is ``False``. While ``put()`` calls are waiting,
``put_nowait()`` raises :exc:`~asyncio.QueueFull` even right after
``get_nowait()``. A task that gets an item and puts it back while other
``put()`` calls are waiting now waits behind them, so a single consumer
that re-queues items can deadlock. Subclasses that override ``put()`` and
wait in the private ``_putters`` deque keep the previous behavior.
(Contributed by Andrew Svetlov in :gh:`83055`.)

* In :mod:`tkinter`, the *name* parameter of the
:meth:`~tkinter.Misc.wait_variable`, :meth:`~tkinter.Misc.setvar` and
:meth:`~tkinter.Misc.getvar` methods and the *value* parameter of
Expand Down
52 changes: 44 additions & 8 deletions Lib/asyncio/queues.py
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,13 @@ def __init__(self, maxsize=0):
self._getters = collections.deque()
# Futures.
self._putters = collections.deque()
# Futures of waiting put() calls. Subclasses may add their own
# futures to self._putters; those never get a reserved slot.
self._own_putters = set()
# Futures of put() calls that were woken up for a freed slot but
# have not run yet. Counting them in full() keeps a newcomer from
# taking the slot and overtaking the waiting putters.
self._reserved = set()
self._unfinished_tasks = 0
self._finished = locks.Event()
self._finished.set()
Expand Down Expand Up @@ -114,27 +121,45 @@ def empty(self):
def full(self):
"""Return True if there are maxsize items in the queue.

Free slots reserved for waiting put() calls count as items.

Note: if the Queue was initialized with maxsize=0 (the default),
then full() is never True.
"""
if self._maxsize <= 0:
return False
else:
return self.qsize() >= self._maxsize
return self.qsize() + len(self._reserved) >= self._maxsize

def _wakeup_next_putter(self):
if not self.full():
while self._putters:
putter = self._putters.popleft()
if not putter.done():
putter.set_result(None)
if (not self._is_shutdown
and putter in self._own_putters):
self._reserved.add(putter)
break

async def put(self, item):
"""Put an item into the queue.

Put an item into the queue. If the queue is full, wait until a free
slot is available before adding item.
slot is available before adding item. Also wait, even if the queue
is not full, behind earlier put() calls that were woken up but have
not run yet.

Raises QueueShutDown if the queue has been shut down.
"""
while self.full():
wait = bool(self._reserved)
while wait or self.full():
wait = False
if self._is_shutdown:
raise QueueShutDown
putter = self._get_loop().create_future()
self._putters.append(putter)
self._own_putters.add(putter)
try:
await putter
except:
Expand All @@ -146,12 +171,22 @@ async def put(self, item):
# The putter could be removed from self._putters by a
# previous get_nowait call or a shutdown call.
pass
if not self.full() and not putter.cancelled():
if putter in self._reserved:
# We were woken up by get_nowait(), but can't take
# the call. Wake up the next in line.
self._wakeup_next(self._putters)
# the call. Pass the reserved slot to the next in line.
self._reserved.remove(putter)
self._wakeup_next_putter()
elif not putter.cancelled():
self._wakeup_next_putter()
raise
return self.put_nowait(item)
finally:
self._own_putters.discard(putter)
self._reserved.discard(putter)
try:
return self.put_nowait(item)
finally:
if self._putters:
self._wakeup_next_putter()

def put_nowait(self, item):
"""Put an item into the queue without blocking.
Expand Down Expand Up @@ -214,7 +249,7 @@ def get_nowait(self):
raise QueueShutDown
raise QueueEmpty
item = self._get()
self._wakeup_next(self._putters)
self._wakeup_next_putter()
return item

def task_done(self):
Expand Down Expand Up @@ -262,6 +297,7 @@ def shutdown(self, immediate=False):
is reduced to zero, callers of Queue.join are unblocked.
"""
self._is_shutdown = True
self._reserved.clear()
if immediate:
while not self.empty():
self._get()
Expand Down
Loading
Loading