【发布时间】:2015-10-01 13:58:54
【问题描述】:
假设我有以下代码:
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 的方法。
【问题讨论】:
-
"I can't get rid of separate thread, because in my real code I use a separate thread to communicate with a serial device"-- 您是否尝试过使用loop.run_in_executor与串行设备进行任何阻塞交互?
标签: python python-3.x python-asyncio