Skip to content

Instantly share code, notes, and snippets.

@cgarciae
Last active June 6, 2019 18:57
Show Gist options
  • Save cgarciae/6d069a000cdd79f50c746199fa9597b2 to your computer and use it in GitHub Desktop.
Save cgarciae/6d069a000cdd79f50c746199fa9597b2 to your computer and use it in GitHub Desktop.
task_pool.py
import asyncio
class TaskPool(object):
def __init__(self, workers):
self._semaphore = asyncio.Semaphore(workers)
self._tasks = set()
async def put(self, coro):
await self._semaphore.acquire()
task = asyncio.ensure_future(coro)
self._tasks.add(task)
task.add_done_callback(self._on_task_done)
def _on_task_done(self, task):
self._tasks.remove(task)
self._semaphore.release()
async def join(self):
await asyncio.gather(*self._tasks)
async def __aenter__(self):
return self
def __aexit__(self, exc_type, exc, tb):
return self.join()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment