asyncio 系列三、asyncio 队列

asyncio 队列

class asyncio.Queue(maxsize=0*loop=None)

先进,先出(FIFO)队列

如果 maxsize 小于等于零,则队列尺寸是无限的。如果是大于 0 的整数,则当队列达到 maxsize 时, awaitput() 将阻塞至某个元素被 get() 取出。

不像标准库中的并发型 queue ,队列的尺寸一直是已知的,可以通过调用 qsize() 方法返回。

这个类 不是线程安全的

 

maxsize

队列中可存放的元素数量。

 

empty()

如果队列为空返回 True ,否则返回 False 。

 

full()

如果有 maxsize 个条目在队列中,则返回 True 。

如果队列用 maxsize=0 (默认)初始化,则 full() 永远不会返回 True 。

coroutine get()

从队列中删除并返回一个元素。如果队列为空,则等待,直到队列中有元素。

get_nowait()

立即返回一个队列中的元素,如果队列内有值,否则引发异常 QueueEmpty 。

 

coroutine join()

阻塞至队列中所有的元素都被接收和处理完毕。

当条目添加到队列的时候,未完成任务的计数就会增加。每当消费协程调用 task_done() 表示这个条目已经被回收,该条目所有工作已经完成,未完成计数就会减少。当未完成计数降到零的时候, join() 阻塞被解除。

 

coroutine put(item)

添加一个元素进队列。如果队列满了,在添加元素之前,会一直等待空闲插槽可用。

 

put_nowait(item)

不阻塞的放一个元素入队列。

如果没有立即可用的空闲槽,引发 QueueFull 异常。

 

qsize()

返回队列用的元素数量。

 

task_done()

表明前面排队的任务已经完成,即get出来的元素相关操作已经完成。

由队列使用者控制。每个 get() 用于获取一个任务,任务最后调用 task_done() 告诉队列,这个任务已经完成。

如果 join() 当前正在阻塞,在所有条目都被处理后,将解除阻塞(意味着每个 put() 进队列的条目的 task_done() 都被收到)。

如果被调用的次数多于放入队列中的项目数量,将引发 ValueError 。

 

优先级队列

class asyncio.PriorityQueue

Queue 的变体;按优先级顺序取出条目 (最小的先取出)。

条目通常是 (priority_number, data) 形式的元组。

后进先出队列

class asyncio.LifoQueue

Queue 的变体,先取出最近添加的条目(后进,先出)。

异常

exception asyncio.QueueEmpty

当队列为空的时候,调用 get_nowait() 方法而引发这个异常。

exception asyncio.QueueFull

当队列中条目数量已经达到它的 maxsize 的时候,调用 put_nowait() 方法而引发的异常。

 

官网例子:

 

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())

 

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,下面是一个使用 asyncio.Queue() 对象管理任务队列的示例代码: ```python import asyncio async def worker(name, queue): while True: # 从队列中获取任务 task = await queue.get() print(f'{name} got task: {task}') # 模拟任务处理过程 await asyncio.sleep(1) # 标记任务完成 queue.task_done() async def main(): # 创建队列对象 queue = asyncio.Queue() # 启动两个 worker workers = [worker(f'worker-{i}', queue) for i in range(2)] await asyncio.gather(*workers) # 向队列中添加任务 for i in range(5): await queue.put(f'task-{i}') # 等待所有任务完成 await queue.join() print('All tasks done!') # 运行主程序 asyncio.run(main()) ``` 在这个示例中,我们创建了一个 `worker` 协程函数,它会不断地从队列中获取任务,并进行处理。我们启动了两个这样的协程,以便能够并发地处理任务。 在主程序中,我们创建了一个 `asyncio.Queue()` 对象,用于存放待执行的任务。然后向队列中添加了 5 个任务。通过 `await queue.join()`,我们等待所有任务完成。 当一个任务完成时,我们需要调用 `queue.task_done()` 来标记任务已经完成。这样,`await queue.join()` 才会在所有任务都完成的时候返回。 运行上述代码,你会看到类似如下的输出: ``` worker-0 got task: task-0 worker-1 got task: task-1 worker-0 got task: task-2 worker-1 got task: task-3 worker-0 got task: task-4 All tasks done! ``` 这表明两个 worker 协程函数同时从队列中获取任务,然后交替地处理它们。当所有任务都完成时,程序输出了 `All tasks done!`。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值