zoukankan      html  css  js  c++  java
  • 使用 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()]))    
    

      

  • 相关阅读:
    “访问”美术馆
    加分二叉树
    有线电视网
    二叉苹果树
    鬼子进村
    遍历问题
    最大子树和
    FBI树
    求前序遍历
    JS如何实现点击页面内任意的链接均加参数跳转?
  • 原文地址:https://www.cnblogs.com/inshua/p/8042799.html
Copyright © 2011-2022 走看看