Skip to content

Commit 9d59381

Browse files
miss-islingtonkumaraditya303asvetlov
authored
[3.10] bpo-45997: Fix asyncio.Semaphore re-acquiring order (GH-31910) (#32047)
Co-authored-by: Kumar Aditya <[email protected]> (cherry picked from commit 32e7715) Co-authored-by: Andrew Svetlov <[email protected]>
1 parent c353835 commit 9d59381

File tree

3 files changed

+37
-6
lines changed

3 files changed

+37
-6
lines changed

Lib/asyncio/locks.py

Lines changed: 10 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@
66

77
from . import exceptions
88
from . import mixins
9+
from . import tasks
910

1011

1112
class _ContextManagerMixin:
@@ -350,6 +351,7 @@ def __init__(self, value=1, *, loop=mixins._marker):
350351
raise ValueError("Semaphore initial value must be >= 0")
351352
self._value = value
352353
self._waiters = collections.deque()
354+
self._wakeup_scheduled = False
353355

354356
def __repr__(self):
355357
res = super().__repr__()
@@ -363,6 +365,7 @@ def _wake_up_next(self):
363365
waiter = self._waiters.popleft()
364366
if not waiter.done():
365367
waiter.set_result(None)
368+
self._wakeup_scheduled = True
366369
return
367370

368371
def locked(self):
@@ -378,16 +381,17 @@ async def acquire(self):
378381
called release() to make it larger than 0, and then return
379382
True.
380383
"""
381-
while self._value <= 0:
384+
# _wakeup_scheduled is set if *another* task is scheduled to wakeup
385+
# but its acquire() is not resumed yet
386+
while self._wakeup_scheduled or self._value <= 0:
382387
fut = self._get_loop().create_future()
383388
self._waiters.append(fut)
384389
try:
385390
await fut
386-
except:
387-
# See the similar code in Queue.get.
388-
fut.cancel()
389-
if self._value > 0 and not fut.cancelled():
390-
self._wake_up_next()
391+
# reset _wakeup_scheduled *after* waiting for a future
392+
self._wakeup_scheduled = False
393+
except exceptions.CancelledError:
394+
self._wake_up_next()
391395
raise
392396
self._value -= 1
393397
return True

Lib/test/test_asyncio/test_locks.py

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -933,6 +933,32 @@ async def test_release_no_waiters(self):
933933
sem.release()
934934
self.assertFalse(sem.locked())
935935

936+
async def test_acquire_fifo_order(self):
937+
sem = asyncio.Semaphore(1)
938+
result = []
939+
940+
async def coro(tag):
941+
await sem.acquire()
942+
result.append(f'{tag}_1')
943+
await asyncio.sleep(0.01)
944+
sem.release()
945+
946+
await sem.acquire()
947+
result.append(f'{tag}_2')
948+
await asyncio.sleep(0.01)
949+
sem.release()
950+
951+
t1 = asyncio.create_task(coro('c1'))
952+
t2 = asyncio.create_task(coro('c2'))
953+
t3 = asyncio.create_task(coro('c3'))
954+
955+
await asyncio.gather(t1, t2, t3)
956+
957+
self.assertEqual(
958+
['c1_1', 'c2_1', 'c3_1', 'c1_2', 'c2_2', 'c3_2'],
959+
result
960+
)
961+
936962

937963
if __name__ == '__main__':
938964
unittest.main()
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
Fix :class:`asyncio.Semaphore` re-aquiring FIFO order.

0 commit comments

Comments
 (0)