Skip to content

Commit

Permalink
Add finished
Browse files Browse the repository at this point in the history
  • Loading branch information
drew2a committed Mar 3, 2023
1 parent 4cf5990 commit b2f3fbc
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 3 deletions.
17 changes: 14 additions & 3 deletions src/tribler/core/utilities/async_group/async_group.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
from typing import Coroutine, Iterable, List, Optional, Set
from weakref import ref

from tribler.core.utilities.async_group.exceptions import CanceledException
from tribler.core.utilities.async_group.exceptions import CanceledException, FinishedException


def done_callback(group_ref):
Expand Down Expand Up @@ -54,6 +54,7 @@ def __init__(self):
self.ref = ref(self)
self.futures: Set[Future] = set()
self._canceled = False
self._finished = False

def add_task(self, coroutine: Coroutine) -> Task:
"""Add a coroutine to the group.
Expand All @@ -64,6 +65,10 @@ def add_task(self, coroutine: Coroutine) -> Task:
task.cancel()
raise CanceledException()

if self._finished:
task.cancel()
raise FinishedException()

self.futures.add(task)
self.global_futures.add(task)

Expand All @@ -73,8 +78,10 @@ def add_task(self, coroutine: Coroutine) -> Task:
async def wait(self):
""" Wait for completion of all futures
"""
if self.futures:
await asyncio.wait(self.futures)
while active := set(self._active(self.futures)):
await asyncio.wait(active)

self._finished = True

async def cancel(self) -> List[Future]:
"""Cancel the group.
Expand All @@ -99,6 +106,10 @@ async def cancel(self) -> List[Future]:
def cancelled(self):
return self._canceled

@property
def finished(self):
return self._finished

@staticmethod
def _active(futures: Iterable[Future]) -> Iterable[Future]:
return (future for future in futures if not future.done())
Expand Down
4 changes: 4 additions & 0 deletions src/tribler/core/utilities/async_group/exceptions.py
Original file line number Diff line number Diff line change
@@ -1,2 +1,6 @@
class CanceledException(Exception):
"""A coroutine can not be added to a cancelled AsyncGroup"""


class FinishedException(Exception):
"""A coroutine can not be added to a finished AsyncGroup"""

0 comments on commit b2f3fbc

Please sign in to comment.