【发布时间】:2018-02-18 19:14:03
【问题描述】:
我的生产者/消费者协程中的错误可能会将项目和未完成的任务留在异步队列中。如果遇到错误,我想简单地停止循环,取消挂起的任务并清除队列。虽然我可以完成前两件事,但我找不到清除队列的简单方法。看完this answer,我想出了三个方法:
import asyncio
q=asyncio.Queue()
for i in range(5):
q.put_nowait(i)
q.get_nowait()
loop=asyncio.get_event_loop()
#this will raise an error if q cannot join
loop.run_until_complete(asyncio.wait_for(q.join(),1))
#method 1
q._queue.clear()
q._finished.set()
q._unfinished_tasks = 0
#method 2
for _ in range(q.qsize()):
q.get_nowait()
for _ in range(q._unfinished_tasks):
q.task_done()
#method 3
del q
q=asyncio.Queue()
那么哪个更好呢?
【问题讨论】:
-
@Vincent 你现在用的是什么方法?
标签: python python-3.x python-asyncio