码迷,mamicode.com
首页 > 其他好文 > 详细

使用 ayncio 实现 CountDownLatch

时间:2017-12-15 15:06:59      阅读:156      评论:0      收藏:0      [点我收藏+]

标签:try   nbsp   random   exception   start   pos   run   with   post   

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

标签:try   nbsp   random   exception   start   pos   run   with   post   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!