如果我正确地理解了您想要什么,就没有什么可以阻止您将Future传递给主线程,以便在func_for_main_thread完成后将其设置为done。在后台线程你可以等待这个未来。在
换句话说:import asyncio
from functools import partial
async def called_threadsafe(loop, func):
current_loop = asyncio.get_event_loop()
fut = asyncio.Future()
def call_and_set():
try:
res = func()
except Exception as exc:
f = partial(fut.set_exception, exc)
current_loop.call_soon_threadsafe(f)
else:
f = partial(fut.set_result, res)
current_loop.call_soon_threadsafe(f)
loop.call_soon_threadsafe(call_and_set) # submit to execute in other thread
return await fut # in current thread await other thread executed func and set future
演示如何工作的完整代码:
^{pr2}$
输出:fg_main started 2252
bg_main started 5568
executed in fg thread 2252
got result in bg thread 5568
bg_main finished 5568
fg_main finished 2252