Skip to content
Open
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
13 changes: 13 additions & 0 deletions Doc/library/asyncio-queue.rst
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,13 @@ 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`.

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

.. method:: get()
:async:

Expand Down Expand Up @@ -90,6 +97,12 @@ 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 freed
slot cannot be taken by a later :meth:`put` or :meth:`put_nowait`.

.. 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
8 changes: 8 additions & 0 deletions Doc/whatsnew/3.16.rst
Original file line number Diff line number Diff line change
Expand Up @@ -1411,6 +1411,14 @@ 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`. 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
35 changes: 30 additions & 5 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,13 +121,25 @@ 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._is_shutdown and not self.full():
while self._putters:
putter = self._putters.popleft()
if not putter.done():
putter.set_result(None)
if putter in self._own_putters:
self._reserved.add(putter)
break

async def put(self, item):
"""Put an item into the queue.
Expand All @@ -135,6 +154,7 @@ async def put(self, item):
raise QueueShutDown
putter = self._get_loop().create_future()
self._putters.append(putter)
self._own_putters.add(putter)
try:
await putter
except:
Expand All @@ -146,11 +166,15 @@ 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()
raise
finally:
self._own_putters.discard(putter)
self._reserved.discard(putter)
return self.put_nowait(item)
Comment thread
asvetlov marked this conversation as resolved.
Resolved

def put_nowait(self, item):
Expand Down Expand Up @@ -214,7 +238,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 +286,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
142 changes: 142 additions & 0 deletions Lib/test/test_asyncio/test_queues.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
import asyncio
import unittest
from types import GenericAlias
from test import support


def tearDownModule():
Expand Down Expand Up @@ -431,6 +432,147 @@ async def test_cancelled_put_silence_value_error_exception(self):
with self.assertRaises(asyncio.CancelledError):
await put_task

async def test_put_nowait_does_not_steal_slot_from_woken_putter(self):
# gh-83055: the slot freed by get_nowait() belongs to the
# woken putter until it runs.
q = asyncio.Queue(1)
q.put_nowait(0)
put_1 = asyncio.create_task(q.put(1))
put_2 = asyncio.create_task(q.put(2))
await asyncio.sleep(0)

self.assertEqual(q.get_nowait(), 0)
self.assertTrue(q.full())
with self.assertRaises(asyncio.QueueFull):
q.put_nowait(3)

self.assertEqual(await q.get(), 1)
self.assertEqual(await q.get(), 2)
await put_1
await put_2
self.assertFalse(q._reserved)

async def test_put_nowait_uses_unreserved_slots(self):

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This test makes me deeply uncomfortable. Because, IMO, for an asyncio.Queue to be fair, it should not be possible to have a successful put_nowait call with pending or/and woken putters regardless of queue's state.(full or not).
But maybe I have missed something.

@asvetlov asvetlov Nov 22, 2026 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

With this PR, put_nowait() can't succeed while a put() is still waiting: every freed slot is reserved for a waiting putter first. The test covers the only remaining case, where there are more free slots than woken putters. Refusing put_nowait() there would raise QueueFull while full() is False, which was the main objection to gh-112501. So the guarantee is that no waiting put() is overtaken or starved, not a strict ordering against woken putters that haven't run yet.

q = asyncio.Queue(2)
q.put_nowait(1)
q.put_nowait(2)
put_3 = asyncio.create_task(q.put(3))
await asyncio.sleep(0)

# Two free slots, only one of them is reserved for put_3.
q.get_nowait()
q.get_nowait()
self.assertFalse(q.full())
q.put_nowait(4)
self.assertTrue(q.full())

await put_3
self.assertEqual(sorted([q.get_nowait(), q.get_nowait()]), [3, 4])
self.assertFalse(q._reserved)

async def test_put_order_with_many_putters(self):
# gh-83055: items must be got in the order put() was called.
q = asyncio.Queue(3)
counter = 0

async def putter(n):
nonlocal counter
for i in range(50):
item = counter
counter += 1
await q.put(item)
if (i + n) % 3 == 0:
await asyncio.sleep(0)

async with asyncio.TaskGroup() as tg:
for n in range(10):
tg.create_task(putter(n))
items = []
for i in range(500):
items.append(await q.get())
if i % 2:
await asyncio.sleep(0)

self.assertEqual(items, sorted(items))
self.assertFalse(q._reserved)

async def test_cancelled_woken_putter_passes_slot_to_next(self):
q = asyncio.Queue(1)
q.put_nowait(0)
put_1 = asyncio.create_task(q.put(1))
put_2 = asyncio.create_task(q.put(2))
await asyncio.sleep(0)

q.get_nowait()
put_1.cancel()
with self.assertRaises(asyncio.CancelledError):
await put_1
await put_2
self.assertEqual(q.get_nowait(), 2)
self.assertFalse(q._reserved)
self.assertFalse(q.full())

async def test_shutdown_with_woken_putter(self):
q = asyncio.Queue(1)
q.put_nowait(0)
put_1 = asyncio.create_task(q.put(1))
await asyncio.sleep(0)

q.get_nowait()
q.shutdown()
with self.assertRaises(asyncio.QueueShutDown):
await put_1
self.assertFalse(q._reserved)

async def test_subclass_with_own_put_loop(self):
# A subclass that waits in self._putters with its own futures
# gets no reserved slot, so it cannot deadlock.
class Q(asyncio.Queue):
async def put(self, item):
while self.full():
putter = self._get_loop().create_future()
self._putters.append(putter)
await putter
self.put_nowait(item)

q = Q(2)

async def producer():
for i in range(10):
await q.put(i)

async with asyncio.timeout(support.SHORT_TIMEOUT):
async with asyncio.TaskGroup() as tg:
tg.create_task(producer())
items = [await q.get() for _ in range(10)]
self.assertEqual(items, list(range(10)))
self.assertFalse(q._reserved)

async def test_subclass_waking_putters_itself(self):
# A put() woken by a subclass without a freed slot was not
# reserved one, so it must not release one either.
class Q(asyncio.Queue):
def peek_nowait(self):
self._wakeup_next(self._putters)
return self._queue[0]

q = Q(2)
q.put_nowait(0)
q.put_nowait(1)
put_2 = asyncio.create_task(q.put(2))
await asyncio.sleep(0)

self.assertEqual(q.peek_nowait(), 0)
await asyncio.sleep(0)
self.assertFalse(put_2.done())
self.assertEqual(q.qsize(), 2)
self.assertFalse(q._reserved)

self.assertEqual(q.get_nowait(), 0)
await put_2
self.assertEqual(list(q._queue), [1, 2])
self.assertFalse(q._reserved)


class LifoQueueTests(unittest.IsolatedAsyncioTestCase):

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
:meth:`asyncio.Queue.get` and :meth:`asyncio.Queue.get_nowait` now reserve
the freed slot for the longest waiting :meth:`asyncio.Queue.put` call, so a
later :meth:`~asyncio.Queue.put` or :meth:`~asyncio.Queue.put_nowait` can no
longer take it and put items out of order. :meth:`asyncio.Queue.full` counts
reserved slots.
Loading