我的请求得到了响应,run_coroutine_threadsafe 函数已在此处实现。
示例:
def target(loop, timeout=None):
future = asyncio.run_coroutine_threadsafe(add(1, b=2), loop)
return future.result(timeout)
async def add(a, b):
await asyncio.sleep(1)
return a + b
loop = asyncio.get_event_loop()
future = loop.run_in_executor(None, target, loop)
assert loop.run_until_complete(future) == 3
我最初发布了一个concurrent.futures.Executor的子类,它仍然可以被实现为:
class LoopExecutor(concurrent.futures.Executor):
"""An Executor subclass that uses an event loop
to execute calls asynchronously."""
def __init__(self, loop=None):
"""Initialize the executor with a given loop."""
self.loop = loop or asyncio.get_event_loop()
def submit(self, fn, *args, **kwargs):
"""Schedule the callable, fn, to be executed as fn(*args **kwargs).
Return a Future object representing the execution of the callable."""
coro = asyncio.coroutine(fn)(*args, **kwargs)
return asyncio.run_coroutine_threadsafe(coro, self.loop)