0
我想盡量創造Java的CountDownLatch
爲什麼condition.notify_all只會喚醒一個服務員?
class CountDownLatch:
def __init__(self, count=1):
if count == 0:
raise ValueError('count should be more than zero')
self.count = count
self.countdown_over = aio.Condition()
async def countdown(self):
with await self.countdown_over:
print('decrementing counter')
self.count -= 1
print('count {}'.format(self.count))
if self.count == 0:
print('count is zero no more waiting')
await aio.sleep(1)
self.countdown_over.notify_all()
async def wait(self):
with await self.countdown_over:
await self.countdown_over.wait()
現在我想要它蟒蛇異步版本。
In [2]: async def g(latch):
...: await latch.wait()
...: print('g')
...:
In [3]: async def f(latch):
...: print('counting down')
...: await latch.countdown()
...: await g(latch)
...:
In [4]: def run():
...: latch = CountDownLatch(2)
...: loop = aio.get_event_loop()
...: loop.run_until_complete(aio.wait((f(latch), f(latch))))
...:
In [5]: import asyncio as aio
In [6]: from new.tests.test_turnovers import CountDownLatch
而這裏的輸出
counting down
decrementing counter
count 1
counting down
decrementing counter
count 0
count is zero no more waiting
g
我不明白我在做什麼錯在這裏。計數器被創建並遞減得很好。一個協程甚至被通知並繼續執行它的任務,但第二個協議並不是出於某種原因。