Python asyncio:在没有创建任务的情况下开始循环

Python asyncio: starting a loop without created task

有人可以解释一下,如果我之前没有添加任何任务就开始循环,为什么我无法执行我的任务? (Python 3.7)

import asyncio
import threading    

def run_forever(loop):
    loop.run_forever()

async def f(x):
    print("%s executed" % x)

# init is called first
def init():
    print("init started")

    loop = asyncio.new_event_loop()

    # loop.create_task(f("a1")) # <--- first commented task

    thread = threading.Thread(target=run_forever, args=(loop,))
    thread.start()

    loop.create_task(f("a2")) # <--- this is not being executed

    print("init finished")

如果我在 # loop.create_task(f("a1")) 上发表评论,执行是:

init started
init finished

未注释的执行是:

init started
init finished
a1 executed
a2 executed

为什么会这样?我想创建一个循环并在将来添加任务。

除非另有明确说明,asyncio API is not thread-safe。这意味着从运行事件循环的线程以外的线程调用 loop.create_task() 将无法与循环正确同步。

要从外部线程将任务提交到事件循环,您需要改为调用asyncio.run_coroutine_threadsafe

asyncio.run_coroutine_threadsafe(f("a2"), loop)

这将唤醒循环以提醒它有新任务到达,并且它还会 returns 一个 concurrent.futures.Future 可用于获取协程的结果。