self: 限制并发量asyncio

  1. #coding:utf-8
  2. import time,asyncio
  3. a=time.time()
  4. id=1
  5. async def hello(id,semaphore):
  6. async with semaphore:
  7. await asyncio.sleep(1)
  8. print('working id:'+str(id))
  9. async def run():
  10. semaphore = asyncio.Semaphore(5) # 限制并发量为5
  11. to_get = [hello(id,semaphore) for id in range(20)] #总共20任务
  12. await asyncio.wait(to_get)
  13. if __name__ == '__main__':
  14. loop = asyncio.get_event_loop()
  15. loop.run_until_complete(run())
  16. loop.close()
  17. print(time.time()-a)
搜索