asyncio_pool.py 598 B

12345678910111213141516171819202122
  1. # -*- coding: utf-8 -*-
  2. # @Time : 2023/7/20 16:10
  3. # @Author : XuJiakai
  4. # @File : async_pool
  5. # @Software: PyCharm
  6. import asyncio
  7. from typing import Coroutine
  8. class AsyncPool(object):
  9. def __init__(self, max_concurrency: int):
  10. self._semaphore: asyncio.Semaphore = asyncio.Semaphore(max_concurrency)
  11. async def create_task(self, coro: Coroutine) -> asyncio.Task:
  12. await self._semaphore.acquire()
  13. task: asyncio.Task = asyncio.create_task(coro)
  14. task.add_done_callback(lambda t: self._semaphore.release())
  15. return task
  16. if __name__ == '__main__':
  17. pass