Python 异步队列与后台线程一起使用时挂起
似乎Python 异步队列与后台线程一起使用时挂起,python,multithreading,async-await,python-multithreading,python-asyncio,Python,Multithreading,Async Await,Python Multithreading,Python Asyncio,似乎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 = a
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
然后就挂了。我错过了什么?你不能直接告诉我
或使用:
或:
其中
loop
是主线程中由asyncio.get\u event\u loop()
返回的循环。您的建议没有成功(挂起方式与以前相同),请您扩展到一个小示例中好吗?啊。需要使用与主线程相同的循环,get\u event\u loop
不适用于此。
loop.call_soon_threadsafe(q.put_nowait, i)
future = asyncio.run_coroutine_threadsafe(q.put(i), loop)