Skip to content

35 故障定位 · 给队列添加高水位和丢弃计数 ​

通过深度、高水位和累计丢弃次数区分当前状态与历史压力。这里用计数模型观察队列占用。

源码 ​

main.c ​

下载 main.c

c
#include <stdio.h>

enum { CAPACITY = 3 };
typedef struct {
    unsigned depth, peak, dropped;
} QueueStats;

static void arrive(QueueStats *s)
{
    if (s->depth == CAPACITY) {
        ++s->dropped;
        return;
    }
    ++s->depth;
    if (s->depth > s->peak) s->peak = s->depth;
}

static void depart(QueueStats *s)
{
    if (s->depth != 0) --s->depth;
}

int main(void)
{
    QueueStats stats = {0};
    for (unsigned i = 0; i < 4; ++i) arrive(&stats);
    depart(&stats);
    depart(&stats);
    printf("depth=%u peak=%u dropped=%u\n", stats.depth, stats.peak, stats.dropped);
    return 0;
}

主机运行 ​

在仓库根目录执行。Windows 可以将输出名写成 reading-35.exe,再从终端运行。

sh
gcc -std=c11 -Wall -Wextra -pedantic examples/c-reading/35/main.c -o reading-35
./reading-35

先沿 main() 预测打印结果,再展开核对。

主机输出与手推
text
depth=1 peak=3 dropped=1

容量 3,连续到达 4 次后丢 1 次;取走 2 项后当前深度 1,历史峰值仍为 3。

练习 ​

构造一次无丢弃的满队列,比较两个指标各能说明什么。

验证记录 ​

主机版使用 GCC 编译运行,输出与跟读材料逐项核对。

上一课 34 · 跟读目录 · 下一课 36