diff options
author | Tin Tvrtković <tinchester@gmail.com> | 2022-02-24 02:17:00 (GMT) |
---|---|---|
committer | GitHub <noreply@github.com> | 2022-02-24 02:17:00 (GMT) |
commit | 7fce1063b6e5a366f8504e039a8ccdd6944625cd (patch) | |
tree | 2c64b18baf6d1515d11b4959d1b1377351126104 /Lib/asyncio | |
parent | 6e117e75c35507f170f6a789538136477f9f226d (diff) | |
download | cpython-7fce1063b6e5a366f8504e039a8ccdd6944625cd.zip cpython-7fce1063b6e5a366f8504e039a8ccdd6944625cd.tar.gz cpython-7fce1063b6e5a366f8504e039a8ccdd6944625cd.tar.bz2 |
bpo-46771: Implement task cancel requests counter (GH-31513)
This changes cancelling() and uncancel() to return the count of pending cancellations.
This can be used to avoid bugs in certain edge cases (e.g. two timeouts going off at the same time).
Diffstat (limited to 'Lib/asyncio')
-rw-r--r-- | Lib/asyncio/tasks.py | 30 |
1 files changed, 21 insertions, 9 deletions
diff --git a/Lib/asyncio/tasks.py b/Lib/asyncio/tasks.py index 25a650f..38c2385 100644 --- a/Lib/asyncio/tasks.py +++ b/Lib/asyncio/tasks.py @@ -105,7 +105,7 @@ class Task(futures._PyFuture): # Inherit Python Task implementation else: self._name = str(name) - self._cancel_requested = False + self._num_cancels_requested = 0 self._must_cancel = False self._fut_waiter = None self._coro = coro @@ -198,13 +198,15 @@ class Task(futures._PyFuture): # Inherit Python Task implementation task will be marked as cancelled when the wrapped coroutine terminates with a CancelledError exception (even if cancel() was not called). + + This also increases the task's count of cancellation requests. """ self._log_traceback = False if self.done(): return False - if self._cancel_requested: + self._num_cancels_requested += 1 + if self._num_cancels_requested > 1: return False - self._cancel_requested = True if self._fut_waiter is not None: if self._fut_waiter.cancel(msg=msg): # Leave self._fut_waiter; it may be a Task that @@ -217,14 +219,24 @@ class Task(futures._PyFuture): # Inherit Python Task implementation return True def cancelling(self): - return self._cancel_requested + """Return the count of the task's cancellation requests. + + This count is incremented when .cancel() is called + and may be decremented using .uncancel(). + """ + return self._num_cancels_requested def uncancel(self): - if self._cancel_requested: - self._cancel_requested = False - return True - else: - return False + """Decrement the task's count of cancellation requests. + + This should be used by tasks that catch CancelledError + and wish to continue indefinitely until they are cancelled again. + + Returns the remaining number of cancellation requests. + """ + if self._num_cancels_requested > 0: + self._num_cancels_requested -= 1 + return self._num_cancels_requested def __step(self, exc=None): if self.done(): |