Skip to content

Commit 670e875

Browse files
committed
Use lock to make sure target started
1 parent f430392 commit 670e875

1 file changed

Lines changed: 13 additions & 6 deletions

File tree

Lib/test/test_asyncio/test_tasks.py

Lines changed: 13 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@
88
import random
99
import re
1010
import sys
11+
from threading import Event
1112
import traceback
1213
import types
1314
import unittest
@@ -3681,15 +3682,21 @@ def task_factory(loop, coro):
36813682
self.assertEqual(context['exception'], exc_context.exception)
36823683

36833684
def test_run_coroutine_threadsafe_and_cancel(self):
3684-
async def target():
3685-
thread_future = asyncio.run_coroutine_threadsafe(self.add(1, 2), self.loop)
3686-
await asyncio.sleep(0)
3685+
target_started = Event()
3686+
async def _target():
3687+
target_started.set()
3688+
await asyncio.sleep(0.1)
3689+
return 1
36873690

3691+
def _in_thread():
3692+
thread_future = asyncio.run_coroutine_threadsafe(_target(), self.loop)
3693+
# wait target started then cancel
3694+
target_started.wait()
36883695
thread_future.cancel()
3689-
await asyncio.sleep(0)
3696+
_ = self.loop.run_in_executor(None, _in_thread)
36903697

3691-
future = self.loop.run_in_executor(None, target)
3692-
self.loop.run_until_complete(future)
3698+
# start main loop to do things
3699+
self.loop.run_until_complete(asyncio.sleep(0.05))
36933700
self.assertEqual(0, len(self.loop._ready))
36943701

36953702

0 commit comments

Comments
 (0)