【问题标题】:async queue hangs when used with background thread与后台线程一起使用时异步队列挂起
【发布时间】:2017-11-06 14:20:03
【问题描述】:

好像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

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

【问题讨论】:

    标签: python multithreading async-await python-multithreading python-asyncio


    【解决方案1】:

    你不能直接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() 返回的循环在您的主线程中

    【讨论】:

    • 你的建议没有成功(和以前一样挂起),你能扩展成一个小例子吗?
    • 啊。需要使用与主线程相同的循环,get_event_loop 不适合。
    猜你喜欢
    • 1970-01-01
    • 2014-10-06
    • 1970-01-01
    • 2018-01-06
    • 1970-01-01
    • 2018-07-29
    • 1970-01-01
    • 2023-02-01
    • 1970-01-01
    相关资源
    最近更新 更多