Skip to content

Commit d7675d3

Browse files
committed
Improve test case
1 parent 5398219 commit d7675d3

2 files changed

Lines changed: 16 additions & 20 deletions

File tree

Lib/asyncio/futures.py

Lines changed: 4 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -365,25 +365,6 @@ def _copy_future_state(source, dest):
365365
else:
366366
dest.set_result(result)
367367

368-
369-
def _cancel_future_in_loop(fut, loop, timeout=None):
370-
"""Cancel a future in (maybe another) event loop.
371-
372-
We need to check loop is not running loop to avoid dead lock.
373-
"""
374-
if loop is None or loop is events._get_running_loop():
375-
return fut.cancel()
376-
cancel_fut = concurrent.futures.Future()
377-
def _cancel():
378-
try:
379-
result = fut.cancel()
380-
cancel_fut.set_result(result)
381-
except BaseException as exc:
382-
cancel_fut.set_exception(exc)
383-
loop.call_soon_threadsafe(_cancel)
384-
return cancel_fut.result(timeout=timeout)
385-
386-
387368
def _chain_future(source, destination):
388369
"""Chain two futures so that when one completes, so does the other.
389370
@@ -408,7 +389,10 @@ def _set_state(future, other):
408389

409390
def _call_check_cancel(destination):
410391
if destination.cancelled():
411-
_cancel_future_in_loop(source, source_loop)
392+
if source_loop is None or source_loop is events._get_running_loop():
393+
source.cancel()
394+
else:
395+
source_loop.call_soon_threadsafe(source.cancel)
412396

413397
def _call_set_state(source):
414398
if (destination.cancelled() and

Lib/test/test_asyncio/test_tasks.py

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3680,6 +3680,18 @@ def task_factory(loop, coro):
36803680
(loop, context), kwargs = callback.call_args
36813681
self.assertEqual(context['exception'], exc_context.exception)
36823682

3683+
def test_run_coroutine_threadsafe_and_cancel(self):
3684+
async def target():
3685+
# self.loop.run_in_executor(None, _in_another_thread)
3686+
thread_future = asyncio.run_coroutine_threadsafe(self.add(1, 2), self.loop)
3687+
await asyncio.sleep(0)
3688+
3689+
thread_future.cancel()
3690+
await asyncio.sleep(0)
3691+
3692+
self.loop.run_until_complete(target())
3693+
self.assertEqual(0, len(self.loop._ready))
3694+
36833695

36843696
class SleepTests(test_utils.TestCase):
36853697
def setUp(self):

0 commit comments

Comments
 (0)