问题描述
消费者基本上是在一个共享队列上迭代,但是,有趣的是,当消费速度比生产速度快时,如下所示,下面的代码将在迭代器处被阻塞,并且push_queue中的while循环也是被屏蔽了。
class Ntest(object):
def __init__(self,q):
self.queue = q
async def push_queue(self) -> None:
counter = 0
while True:
self.queue.put(str(counter))
await asyncio.sleep(2)
counter = counter + 1
async def print_queue(self) -> None:
for elem in iter(self.queue.get,None):
await asyncio.sleep(1)
print(elem)
async def main():
q = queue.Queue()
ntest = Ntest(q)
await asyncio.gather(ntest.push_queue(),ntest.print_queue())
if __name__ == '__main__':
asyncio.run(main())
有人可以向我解释为什么它会以这种方式被阻塞,因为我期望 push_queue 会继续将项目推入队列,而 print_queue 只会在队列为空时被阻塞?
解决方法
您在这里使用同步队列 q = queue.Queue()
这会导致阻塞。
请使用 asyncio.Queue https://docs.python.org/3.6/library/asyncio-queue.html 使其异步工作