Skip to content

Commit

Permalink
Merge pull request #909 from oremanj/cancel_immediately
Browse files Browse the repository at this point in the history
Cancel a cancel scope upon entry if its deadline is in the past
  • Loading branch information
njsmith authored Feb 6, 2019
2 parents ccb6023 + 0f90296 commit 0a815a0
Show file tree
Hide file tree
Showing 4 changed files with 19 additions and 7 deletions.
4 changes: 4 additions & 0 deletions newsfragments/320.misc.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
Entering a cancel scope whose deadline is in the past now immediately
cancels it, so :exc:`~trio.Cancelled` will be raised by the first
checkpoint in the cancel scope rather than the second one.
This also affects constructs like ``with trio.move_on_after(0):``.
2 changes: 2 additions & 0 deletions trio/_core/_run.py
Original file line number Diff line number Diff line change
Expand Up @@ -201,6 +201,8 @@ def __enter__(self):
)
self._scope_task = task
self.cancelled_caught = False
if current_time() >= self._deadline:
self.cancel_called = True
with self._might_change_effective_deadline():
self._add_task(task)
return self
Expand Down
18 changes: 12 additions & 6 deletions trio/_core/tests/test_run.py
Original file line number Diff line number Diff line change
Expand Up @@ -407,12 +407,18 @@ async def main():

_core.run(main, instruments=[r1, r2])

# It sleeps 5 times, so it runs 6 times
# It sleeps 5 times, so it runs 6 times. Note that checkpoint()
# reschedules the task immediately upon yielding, before the
# after_task_step event fires.
expected = (
[("before_run",)] +
6 * [("schedule", task),
[("before_run",),
("schedule", task)] +
[("before", task),
("schedule", task),
("after", task)] * 5 + [
("before", task),
("after", task)] + [("after_run",)]
("after", task), ("after_run",)
]
)
assert len(r1.record) > len(r2.record) > len(r3.record)
assert r1.record == r2.record + r3.record
Expand Down Expand Up @@ -444,15 +450,15 @@ async def main():
("schedule", tasks["t2"]),
{
("before", tasks["t1"]),
("schedule", tasks["t1"]),
("after", tasks["t1"]),
("before", tasks["t2"]),
("schedule", tasks["t2"]),
("after", tasks["t2"])
},
{
("schedule", tasks["t1"]),
("before", tasks["t1"]),
("after", tasks["t1"]),
("schedule", tasks["t2"]),
("before", tasks["t2"]),
("after", tasks["t2"])
},
Expand Down
2 changes: 1 addition & 1 deletion trio/_core/tests/tutil.py
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@ def gc_collect_harder():


# template is like:
# [1, {2.1, 2.2}, 3] -> matches [1, 2.1, 3] or [1, 2.2, 3]
# [1, {2.1, 2.2}, 3] -> matches [1, 2.1, 2.2, 3] or [1, 2.2, 2.1, 3]
def check_sequence_matches(seq, template):
i = 0
for pattern in template:
Expand Down

0 comments on commit 0a815a0

Please sign in to comment.