queue.join() 和 task.cancel()的调用位置 不太理解。。

来源:4-9 tornado实现高并发的爬虫

慕UI9336467

2020-03-13

官方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())
写回答

1回答

慕UI9336467

提问者

2020-03-13

我发现await asyncio.gather(*tasks, return_exceptions = Ture)这句代码是多余的

0
1
bobby
await asyncio.gather(*tasks, return_exceptions=True)的作用是等待所有的任务执行完成
2020-03-14
共1条回复

Tornado从入门到进阶 打造支持高并发的技术论坛

异步IO并发编程/Form,ORM/aiomysql、peewee-async/epoll

595 学习 · 350 问题

查看课程