]> git.ipfire.org Git - thirdparty/Python/cpython.git/commitdiff
[3.9] bpo-45997: Fix asyncio.Semaphore re-acquiring order (GH-31910) (GH-32049)
authorAndrew Svetlov <andrew.svetlov@gmail.com>
Tue, 22 Mar 2022 15:16:27 +0000 (17:16 +0200)
committerGitHub <noreply@github.com>
Tue, 22 Mar 2022 15:16:27 +0000 (17:16 +0200)
Co-authored-by: Kumar Aditya <59607654+kumaraditya303@users.noreply.github.com>.
(cherry picked from commit 32e77154ddfc514a3144d5912bffdd957246fd6c)

Co-authored-by: Andrew Svetlov <andrew.svetlov@gmail.com>
Lib/asyncio/locks.py
Lib/test/test_asyncio/test_locks.py
Misc/NEWS.d/next/Library/2022-03-15-18-32-12.bpo-45997.4n2aVU.rst [new file with mode: 0644]

index f1ce7324785ba983b8ba12f3283a70757ad0cc86..d17d7ccd813d2a32554d37557af23b73bfac5841 100644 (file)
@@ -378,6 +378,7 @@ class Semaphore(_ContextManagerMixin):
             warnings.warn("The loop argument is deprecated since Python 3.8, "
                           "and scheduled for removal in Python 3.10.",
                           DeprecationWarning, stacklevel=2)
+        self._wakeup_scheduled = False
 
     def __repr__(self):
         res = super().__repr__()
@@ -391,6 +392,7 @@ class Semaphore(_ContextManagerMixin):
             waiter = self._waiters.popleft()
             if not waiter.done():
                 waiter.set_result(None)
+                self._wakeup_scheduled = True
                 return
 
     def locked(self):
@@ -406,16 +408,17 @@ class Semaphore(_ContextManagerMixin):
         called release() to make it larger than 0, and then return
         True.
         """
-        while self._value <= 0:
+        # _wakeup_scheduled is set if *another* task is scheduled to wakeup
+        # but its acquire() is not resumed yet
+        while self._wakeup_scheduled or self._value <= 0:
             fut = self._loop.create_future()
             self._waiters.append(fut)
             try:
                 await fut
-            except:
-                # See the similar code in Queue.get.
-                fut.cancel()
-                if self._value > 0 and not fut.cancelled():
-                    self._wake_up_next()
+                # reset _wakeup_scheduled *after* waiting for a future
+                self._wakeup_scheduled = False
+            except exceptions.CancelledError:
+                self._wake_up_next()
                 raise
         self._value -= 1
         return True
index b9aae360384eaf4f01fdd44ad692a5e09fedca80..79ebbd26804a541015143e8d171ca97d091b3cd0 100644 (file)
@@ -961,6 +961,32 @@ class SemaphoreTests(unittest.IsolatedAsyncioTestCase):
         sem.release()
         self.assertFalse(sem.locked())
 
+    async def test_acquire_fifo_order(self):
+        sem = asyncio.Semaphore(1)
+        result = []
+
+        async def coro(tag):
+            await sem.acquire()
+            result.append(f'{tag}_1')
+            await asyncio.sleep(0.01)
+            sem.release()
+
+            await sem.acquire()
+            result.append(f'{tag}_2')
+            await asyncio.sleep(0.01)
+            sem.release()
+
+        t1 = asyncio.create_task(coro('c1'))
+        t2 = asyncio.create_task(coro('c2'))
+        t3 = asyncio.create_task(coro('c3'))
+
+        await asyncio.gather(t1, t2, t3)
+
+        self.assertEqual(
+            ['c1_1', 'c2_1', 'c3_1', 'c1_2', 'c2_2', 'c3_2'],
+            result
+        )
+
 
 if __name__ == '__main__':
     unittest.main()
diff --git a/Misc/NEWS.d/next/Library/2022-03-15-18-32-12.bpo-45997.4n2aVU.rst b/Misc/NEWS.d/next/Library/2022-03-15-18-32-12.bpo-45997.4n2aVU.rst
new file mode 100644 (file)
index 0000000..40d8504
--- /dev/null
@@ -0,0 +1 @@
+Fix :class:`asyncio.Semaphore` re-aquiring FIFO order.