From 841d9ee41a8ad0a8a372f9b84f0fa40b07bcc66b Mon Sep 17 00:00:00 2001 From: Guido van Rossum Date: Sat, 3 Oct 2015 08:31:42 -0700 Subject: Issue #25304: Add asyncio.run_coroutine_threadsafe(). By Vincent Michel. --- Lib/asyncio/tasks.py | 18 +++++++++++++++++- 1 file changed, 17 insertions(+), 1 deletion(-) (limited to 'Lib/asyncio/tasks.py') diff --git a/Lib/asyncio/tasks.py b/Lib/asyncio/tasks.py index 434f498e47..5a7bd9dbcb 100644 --- a/Lib/asyncio/tasks.py +++ b/Lib/asyncio/tasks.py @@ -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 -- cgit v1.2.1