好吧,我正在研究python文档以研究我的工作。我是python和编程的新手,我也不太了解异步操作之类的编程概念。
我将Fedora 29与Python 3.7.3结合使用来尝试队列和lib asyncio的示例。
按照下面的队列和异步操作示例:
import asyncio
import random
import time
async def worker(name, queue):
while True:
# Get a "work item" out of the queue.
sleep_for = await queue.get()
# Sleep for the "sleep_for" seconds.
await asyncio.sleep(sleep_for)
# Notify the queue that the "work item" has been processed.
queue.task_done()
print(f'{name} has slept for {sleep_for:.2f} seconds')
async def main():
# Create a queue that we will use to store our "workload".
queue = asyncio.Queue()
# Generate random timings and put them into the queue.
total_sleep_time = 0
for _ in range(20):
sleep_for = random.uniform(0.05, 1.0)
total_sleep_time += sleep_for
queue.put_nowait(sleep_for)
# Create three worker tasks to process the queue concurrently.
tasks = []
for i in range(3):
task = asyncio.create_task(worker(f'worker-{i}', queue))
tasks.append(task)
# Wait until the queue is fully processed.
started_at = time.monotonic()
await queue.join()
total_slept_for = time.monotonic() - started_at
# Cancel our worker tasks.
for task in tasks:
task.cancel()
# Wait until all worker tasks are cancelled.
await asyncio.gather(*tasks, return_exceptions=True)
print('====')
print(f'3 workers slept in parallel for {total_slept_for:.2f} seconds')
print(f'total expected sleep time: {total_sleep_time:.2f} seconds')
asyncio.run(main())
为什么在此示例中我需要取消任务?为什么我可以排除这部分代码
# Cancel our worker tasks.
for task in tasks:
task.cancel()
# Wait until all worker tasks are cancelled.
await asyncio.gather(*tasks, return_exceptions=True)
示例可以正常工作吗?
答案 0 :(得分:0)
为什么在此示例中我需要取消任务?
因为否则它们将无限期地挂起,等待队列中永远不会到达的新项目。在该特定示例中,无论如何您都将退出事件循环,因此它们“挂起”没有什么害处,但是如果将其作为实用程序功能的一部分进行操作,则会创建协程泄漏。
换句话说,取消工作人员会告知他们退出,因为他们不再需要他们的服务,并且需要确保与他们相关的资源被释放。