1. 程式人生 > >self: 限制併發量asyncio

self: 限制併發量asyncio

#coding:utf-8
import time,asyncio

a=time.time()

id=1
async def hello(id,semaphore):
    async with semaphore:
        await asyncio.sleep(1)
        print('working id:'+str(id))

async def run():
    semaphore = asyncio.Semaphore(5) # 限制併發量為5
    to_get = [hello(id,semaphore) for id in range(20)] #總共20任務
    await asyncio.wait(to_get)


if __name__ == '__main__':
    loop = asyncio.get_event_loop()
    loop.run_until_complete(run())
    loop.close()
    print(time.time()-a)