假设我有以下代码:
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
的大小却在增加.
Why is this happening this way and what can I do to fix it?
我无法摆脱单独的线程,因为在我的实际代码中,我使用单独的线程与串行设备通信,而我还没有找到使用asyncio
来实现这一点的方法.