From 8d9b874228c8c1fe714ff4fd1b122bbdafcacb10 Mon Sep 17 00:00:00 2001 From: nocturn9x Date: Mon, 23 Mar 2020 19:49:12 +0000 Subject: [PATCH] Added some TODOs and tried a solution for the cancel() method (and failed) --- experiment.py | 26 +++++++++++++++----------- giambio/core.py | 10 +++++++--- 2 files changed, 22 insertions(+), 14 deletions(-) diff --git a/experiment.py b/experiment.py index 9e153c2..3c5d841 100644 --- a/experiment.py +++ b/experiment.py @@ -28,21 +28,25 @@ async def countdown(n): print("countdown cancelled!") async def count(stop, step=1): - x = 0 - while x < stop: - print(f"Up {x}") - x += step - await giambio.sleep(step) - print("Countup over") - return "Count UP over" - + try: + x = 0 + while x < stop: + print(f"Up {x}") + x += step + await giambio.sleep(step) + print("Countup over") + return "Count UP over" + except giambio.exceptions.CancelledError: + print("count cancelled!") async def main(): - print("Spawning countdown immediately, scheduling count for 2 secs from now") + print("Spawning countdown immediately, scheduling count for 4 secs from now") task = loop.spawn(countdown(8)) - task1 = loop.schedule(count(8, 2), 2) + task1 = loop.schedule(count(8, 2), 4) + await giambio.sleep(0) # Beware! Cancelling a task straight away will propagate the error in the parent +# await task.cancel() # TODO: Fix this to reschedule the parent task properly result = await task.join() - result1 = await task1.join() # Joining a scheduled task does not reschedule the parent task + result1 = await task1.join() print(f"countdown returned: {result}\ncount returned: {result1}") print("All done") diff --git a/giambio/core.py b/giambio/core.py index 04f7db2..c29b2f8 100644 --- a/giambio/core.py +++ b/giambio/core.py @@ -51,6 +51,8 @@ class EventLoop: except StopIteration as e: self.running.result = Result(e.args[0] if e.args else None, None) # Saves the return value self.to_run.extend(self.joined.pop(self.running, ())) # Reschedules the parent task + except RuntimeError: + self.to_run.append(self.running) except Exception as has_raised: self.to_run.extend(self.joined.pop(self.running, ())) # Reschedules the parent task if self.running.joined: # Let the join function handle the hassle of propagating the error @@ -158,6 +160,7 @@ class Task: self.joined = False self.result = None # Updated when the coroutine execution ends self.loop = loop # The EventLoop object that spawned the task + self.cancelled = False def run(self): self.status = True @@ -210,9 +213,10 @@ def want_write(sock: socket.socket): def join(task: Task): """'Tells' the scheduler that the desired task MUST be awaited for completion""" - task.joined = True - yield "want_join", task - return task.get_result() + if not task.cancelled: + task.joined = True + yield "want_join", task + return task.get_result() @types.coroutine