首页 > 其他 > 详细

使用 ayncio 实现 CountDownLatch

时间:2017-12-15 14:48:28      阅读:262      评论:0      收藏:0      [点我收藏+]
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()]))    

  

使用 ayncio 实现 CountDownLatch

原文:http://www.cnblogs.com/inshua/p/8042799.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!