You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用queuelib实现固定大小持久化磁盘队列遇磁盘占用异常求助

问题原因与解决方案

问题根源

  1. q00000文件始终0KB:FifoDiskQueue默认每个段文件的大小阈值是1MB,你生成的单帧数据转成bytes后只有几十字节,远没达到触发新段文件的条件,所有元素都写入同一个段文件。Windows文件系统对小文件的大小更新可能存在延迟,或者queuelib的写入缓冲未及时刷新,导致文件显示为0KB。
  2. 磁盘空间持续耗尽:这是核心问题——FifoDiskQueue是追加式写入的设计,pop()操作只是移动内部读取指针,标记元素为已消费,但不会删除磁盘上的旧数据。你每次pop()后又push()新元素,队列逻辑长度保持10,但磁盘文件会不断追加新内容,旧的已消费元素一直留在磁盘上,最终把磁盘占满。

正确实现固定大小磁盘队列的方法

queuelib本身不是为循环覆盖旧数据的固定大小队列设计的,推荐两种可行方案:

方案1:基于queuelib的折中实现(适合小规模队列)

因为你的队列固定为10个元素,可以在队列满时,提取剩余需要保留的元素,重建队列后重新写入:

from queuelib import FifoDiskQueue
import numpy as np
import os

QUEUE_SIZE = 10
queue_dir = r"c:\temp"

def init_queue():
    return FifoDiskQueue(queue_dir)

images_data = init_queue()

try:
    while True:
        frame = np.random.rand(3,2)
        if len(images_data) >= QUEUE_SIZE:
            # 移除最老元素,保留剩下的9个
            images_data.pop()
            remaining_items = []
            while len(images_data) > 0:
                remaining_items.append(images_data.pop())
            
            # 清理旧队列文件
            images_data.close()
            for file in os.listdir(queue_dir):
                if file.startswith("q"):
                    os.remove(os.path.join(queue_dir, file))
            
            # 重建队列并写入保留的元素
            images_data = init_queue()
            for item in remaining_items:
                images_data.push(item)
        
        images_data.push(frame.tobytes())
finally:
    images_data.close()

方案2:使用diskcache库(推荐)

diskcache原生支持固定大小的磁盘队列,会自动清理旧元素维持队列大小,比queuelib更适合你的场景:
先安装库:

pip install diskcache

实现代码:

from diskcache import Cache
import numpy as np

QUEUE_SIZE = 10
# 初始化缓存,指定存储目录
cache = Cache(r"c:\temp")
# 创建固定大小的队列,超过maxsize自动删除最老元素
fixed_queue = cache.queue(maxsize=QUEUE_SIZE)

try:
    while True:
        frame = np.random.rand(3,2)
        fixed_queue.put(frame.tobytes())
        # 无需手动处理pop,队列自动维持在10个元素以内
finally:
    cache.close()

内容的提问来源于stack exchange,提问作者DavidDr90

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.24 19:46:17