异步队列在与后台线程一起使用时挂起

async queue hangs when used with background thread

好像asyncio.Queue只能被同线程读取推送吗?例如:

import asyncio
from threading import Thread
import time

q = asyncio.Queue()

def produce():
    for i in range(100):
        q.put_nowait(i)
        time.sleep(0.1)

async def consume():
    while True:
        i = await q.get()
        print('consumed', i)

Thread(target=produce).start()
asyncio.get_event_loop().run_until_complete(consume())

只打印

consumed 0

然后挂起。我错过了什么?

你不能直接call asyncio methods from another thread

或者使用 loop.call_soon_threadsafe:

loop.call_soon_threadsafe(q.put_nowait, i)

asyncio.run_coroutine_threadsafe:

future = asyncio.run_coroutine_threadsafe(q.put(i), loop)

其中 loopasyncio.get_event_loop() 在您的主线程中返回的循环