如何解决为什么迭代器永远阻塞
消费者基本上是在一个共享队列上迭代,但是,有趣的是,当消费速度比生产速度快时,如下所示,下面的代码将在迭代器处被阻塞,并且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 使其异步工作
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。