假設我有以下代碼:有沒有辦法在多個線程中使用asyncio.Queue?
import asyncio
import threading
queue = asyncio.Queue()
def threaded():
import time
while True:
time.sleep(2)
queue.put_nowait(time.time())
print(queue.qsize())
@asyncio.coroutine
def async():
while True:
time = yield from queue.get()
print(time)
loop = asyncio.get_event_loop()
asyncio.Task(async())
threading.Thread(target=threaded).start()
loop.run_forever()
這段代碼的問題是,裏面async
協程循環永遠不會完成第一次迭代,而queue
規模在不斷擴大。
這是爲什麼發生這種情況,我該如何解決這個問題?
我無法擺脫單獨的線程,因爲在我真正的代碼,我使用一個單獨的線程與串行設備進行通信,並且我還沒有找到一個方法來做到這一點使用asyncio
。
'「我無法擺脫單獨的線程,因爲在我真正的代碼,我使用一個單獨的線程與串行設備進行通訊」' - 您是否嘗試過使用'loop.run_in_executor'做任何阻塞的相互作用串行設備? –