使用 ayncio 实现 CountDownLatch
class CountDownLatch(object):
def __init__(self, count=1):
self.count = count
self.lock = asyncio.Lock()
self.event = asyncio.Event()
async def count_down(self):
with await self.lock:
self.count -= 1
if self.count <= 0:
self.event.set()
async def wait(self):
await self.event.wait()
网上没找到好用的,自己实现了一个。
测试:
async def test(latch : CountDownLatch, i):
# await asyncio.sleep(random.random() * 2)
print('{} work complete'.format(i))
await latch.count_down()
async def main():
try:
for j in range(0, 10):
print('turn start')
latch = CountDownLatch(20)
for i in range(0, 20):
asyncio.ensure_future(test(latch, i))
await latch.wait()
print("20 tasks complete")
await asyncio.sleep(2)
except Exception as e:
print(e)
if __name__ == '__main__' :
loop = asyncio.get_event_loop();
loop.run_until_complete(asyncio.wait([main()]))

浙公网安备 33010602011771号