Last active
June 6, 2019 18:57
-
-
Save cgarciae/6d069a000cdd79f50c746199fa9597b2 to your computer and use it in GitHub Desktop.
task_pool.py
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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