Skip to content

0.4.1 环形缓冲区+优先级位图调度器

Choose a tag to compare

@funnywwh funnywwh released this 28 Oct 12:28
· 61 commits to main since this release

ZCO v0.4.1 Release

🎉 主要更新

本版本实现了环形缓冲区+优先级位图调度器,这是调度器架构的重大升级!

✨ 新特性

1. 环形缓冲区+优先级位图调度器

  • O(1) 优先级查找: 使用32位位图实现常数时间查找最高优先级协程
  • 多优先级支持: 支持0-31共32个优先级级别的独立队列
  • O(1) 入队/出队: 每个优先级使用独立的环形缓冲区
  • 内存优化: 环形缓冲区避免频繁内存分配,提高性能

2. 可配置参数

  • RING_BUFFER_SIZE = 2048 - 每个优先级的环形缓冲区大小(可配置)
  • MAX_PRIORITY_LEVELS = 32 - 支持的优先级级别数量

3. 新增 API

// 带优先级的协程创建
pub fn goWithPriority(
    self: *Schedule, 
    comptime func: anytype, 
    args: anytype, 
    priority: usize
) !*Co

// 队列统计信息
pub fn count(self: *const RingBufferPriorityQueue) usize
pub fn isEmpty(self: *const RingBufferPriorityQueue) bool
pub fn getPriorityCount(self: *const RingBufferPriorityQueue, priority: usize) usize
pub fn getHighestPriority(self: *const RingBufferPriorityQueue) ?usize

🚀 性能提升

时间复杂度

  • 查找最高优先级: O(log n) → O(1)
  • 入队操作: O(1) (保持不变)
  • 出队操作: O(1) (保持不变)

内存占用

  • 增加: 约256KB (32 × 2048 × 4字节指针)
  • 优势: 支持32个优先级级别的独立队列,避免动态分配

🔧 技术亮点

优先级位图操作

// 设置优先级位
self.priority_bitmap |= (@as(u32, 1) << @intCast(priority));

// 查找最高优先级 (O(1))
const highest_priority = 31 - @clz(self.priority_bitmap);

// 清除优先级位
self.priority_bitmap &= ~(@as(u32, 1) << @intCast(priority));

环形缓冲区设计

const RingBufferPriorityQueue = struct {
    rings: [MAX_PRIORITY_LEVELS]RingBuffer,  // 32个优先级的环形缓冲区
    priority_bitmap: u32,                     // 32位优先级位图
    allocator: std.mem.Allocator,
};

📖 使用示例

创建不同优先级的协程

// 高优先级协程
_ = try schedule.goWithPriority(highPriorityTask, .{}, 15);

// 中等优先级协程
_ = try schedule.goWithPriority(mediumPriorityTask, .{}, 5);

// 低优先级协程
_ = try schedule.goWithPriority(lowPriorityTask, .{}, 0);

查询队列状态

// 获取总协程数
const total_count = schedule.readyQueue.count();

// 获取最高优先级
if (schedule.readyQueue.getHighestPriority()) |highest| {
    std.log.info("当前最高优先级: {d}", .{highest});
}

// 获取指定优先级的协程数
const count = schedule.readyQueue.getPriorityCount(10);

🧪 测试验证

  • ✅ 基本调度功能正常
  • ✅ 时间片抢占工作正常
  • ✅ 协程交替执行正常
  • ✅ 多优先级调度顺序正确
  • ✅ 环形缓冲区循环使用正常
  • ✅ 位图正确更新

📚 文档

  • 技术文档: docs/RING_BUFFER_PRIORITY_REPORT.md
  • 完整文档: docs/ 目录包含14个文档文件
  • 优化指南: docs/PERFORMANCE_OPTIMIZATION_GUIDE.md

🔗 相关链接

🎯 向后兼容性

  • ✅ 完全向后兼容现有API
  • ✅ 默认优先级为0
  • ✅ 现有代码无需修改即可使用

🙏 致谢

感谢所有贡献者和用户的支持!