Skip to main content
 首页 » 编程设计

python之如何对队列进行切片

2025年01月19日11tintown

我有一个循环处理的队列

while True: 
    # a processing loop 
    batch = [] 
    while True: 
        e = q.get() 
        if e: 
            batch.append(e) 
        else: 
            # the queue is empty 
            break 
    do_something_with(batch) 
    # wait a moment before emptying the queue again 
    time.sleep(2) 

想法是清空队列,处理其内容并稍等片刻,然后再次检查内容。

我有时会遇到竞争条件,即在我 get() 一个元素时队列被填充,我最终得到一个不断增长的 batch,它永远不会被进一步处理。

一种解决方案是检查 batch 大小并在大小合适时对其进行处理。如果我没有那么多事件进入队列并且 batch 从未达到正确的大小,这将不起作用 - 但我需要处理事件(无论它们的数量是多少)而不是等到足够多的积累.

第二种解决方案是根据大小和 batch 空闲时间构建检查——这会使代码过于复杂。

一个好的解决方案是“一次从队列中获取最多 n 个元素”。我在文档中找不到类似的东西。 有没有办法一次从队列中弹出多个元素(类似于列表的切片)?

请您参考如下方法:

Queue.get 默认阻止;无限循环的来源。

Queue.get(block=True, timeout=None)

Remove and return an item from the queue. If optional args block is true and timeout is None (the default), block if necessary until an item is available. If timeout is a positive number, it blocks at most timeout seconds and raises the Empty exception if no item was available within that time. Otherwise (block is false), return an item if one is immediately available, else raise the Empty exception (timeout is ignored in that case).

你应该使用, Queue.get_nowait 或 Queue.get(block=False)以防止阻塞。或者使用 Queue.get(timeout=<seconds>)最多等待<seconds>当队列为空时。

您问题中提到的解决方案听起来不错:

BATCH_SIZE = 10 
 
while True: 
    batch = [] 
 
    # Get out of loop if enough item collected or queue is empty 
    while len(batch) < BATCH_SIZE: 
        try: 
            e = q.get_nowait()  # OR q.get(timeout=0.1) 
        except Empty: 
            break 
            # To prevent empty batch 
            # if batch: 
            #     break 
 
    do_something_with(batch) 
    # wait a moment before emptying the queue again 
    time.sleep(2)