File tree Expand file tree Collapse file tree 1 file changed +10
-4
lines changed Expand file tree Collapse file tree 1 file changed +10
-4
lines changed Original file line number Diff line number Diff line change 6
6
7
7
8
8
class DequeSemaphore :
9
- """Custom deque based semaphore."""
9
+ """
10
+ Custom deque based semaphore.
11
+
12
+ https://neopythonic.blogspot.com/2022/10/reasoning-about-asynciosemaphore.html
13
+ """
10
14
11
15
def __init__ (self , value : int ) -> None :
12
16
self ._value = value
@@ -27,7 +31,9 @@ def locked(self) -> bool:
27
31
28
32
:returns: true or false
29
33
"""
30
- return self ._value == 0
34
+ return self ._value == 0 or (
35
+ any (not waiter .cancelled () for waiter in (self ._waiters or ()))
36
+ )
31
37
32
38
def release (self ) -> None :
33
39
"""Release a semaphore, incrementing the internal counter by one.
@@ -46,7 +52,7 @@ async def acquire(self, first: bool = False) -> Literal[True]: # noqa: C901
46
52
:raises asyncio.exceptions.CancelledError: task cancelled
47
53
:returns: true
48
54
"""
49
- if not self .locked () and not self . _waiters :
55
+ if not self .locked ():
50
56
# No need to wait as the semaphore is not locked
51
57
# and no one is waiting
52
58
self ._value -= 1
@@ -72,7 +78,7 @@ async def acquire(self, first: bool = False) -> Literal[True]: # noqa: C901
72
78
self ._wakeup_next ()
73
79
raise
74
80
75
- if not self .locked () :
81
+ if self ._value > 0 :
76
82
# This is required for strict FIFO ordering
77
83
# otherwise it can cause starvation on the waiting tasks
78
84
# The next loop iteration will wake up the task and switch
You can’t perform that action at this time.
0 commit comments