Issue #25304: Add asyncio.run_coroutine_threadsafe(). By Vincent Michel.

This commit is contained in:
Guido van Rossum 2015-10-03 08:31:42 -07:00
parent 3795d12a0d
commit 841d9ee41a
6 changed files with 147 additions and 19 deletions

View file

@ -3,7 +3,7 @@
__all__ = ['Task',
'FIRST_COMPLETED', 'FIRST_EXCEPTION', 'ALL_COMPLETED',
'wait', 'wait_for', 'as_completed', 'sleep', 'async',
'gather', 'shield', 'ensure_future',
'gather', 'shield', 'ensure_future', 'run_coroutine_threadsafe',
]
import concurrent.futures
@ -692,3 +692,19 @@ def shield(arg, *, loop=None):
inner.add_done_callback(_done_callback)
return outer
def run_coroutine_threadsafe(coro, loop):
"""Submit a coroutine object to a given event loop.
Return a concurrent.futures.Future to access the result.
"""
if not coroutines.iscoroutine(coro):
raise TypeError('A coroutine object is required')
future = concurrent.futures.Future()
def callback():
futures._chain_future(ensure_future(coro, loop=loop), future)
loop.call_soon_threadsafe(callback)
return future