2020-08-20 16:43:44 +02:00
|
|
|
from asyncio import Event, get_running_loop
|
2018-12-07 02:03:22 +01:00
|
|
|
|
|
|
|
|
|
|
|
class TaskGroup:
|
|
|
|
|
|
|
|
def __init__(self, loop=None):
|
2020-08-20 16:43:44 +02:00
|
|
|
self._loop = loop or get_running_loop()
|
2018-12-07 02:03:22 +01:00
|
|
|
self._tasks = set()
|
|
|
|
self.done = Event()
|
2020-03-31 22:20:13 +02:00
|
|
|
self.started = Event()
|
2018-12-07 02:03:22 +01:00
|
|
|
|
2020-03-24 04:54:55 +01:00
|
|
|
def __len__(self):
|
|
|
|
return len(self._tasks)
|
|
|
|
|
2018-12-07 02:03:22 +01:00
|
|
|
def add(self, coro):
|
|
|
|
task = self._loop.create_task(coro)
|
|
|
|
self._tasks.add(task)
|
2020-03-31 22:20:13 +02:00
|
|
|
self.started.set()
|
2018-12-07 02:03:22 +01:00
|
|
|
self.done.clear()
|
|
|
|
task.add_done_callback(self._remove)
|
|
|
|
return task
|
|
|
|
|
|
|
|
def _remove(self, task):
|
|
|
|
self._tasks.remove(task)
|
2019-10-26 20:27:41 +02:00
|
|
|
if len(self._tasks) < 1:
|
|
|
|
self.done.set()
|
2020-03-31 22:20:13 +02:00
|
|
|
self.started.clear()
|
2018-12-07 02:03:22 +01:00
|
|
|
|
|
|
|
def cancel(self):
|
|
|
|
for task in self._tasks:
|
|
|
|
task.cancel()
|
2019-12-12 03:19:18 +01:00
|
|
|
self.done.set()
|
2020-03-31 22:20:13 +02:00
|
|
|
self.started.clear()
|