Skip to content

34 双缓冲 · 观察生产速度超过消费速度 ​

用串行事件模拟采集完成、消费者读取和释放槽位。显式记录没有空槽位时丢弃的新样本。

源码 ​

main.c ​

下载 main.c

c
#include <stdio.h>
#include <stdbool.h>

typedef struct {
    unsigned slots[2];
    unsigned read, write, used, lost;
} Capture;

static void complete(Capture *c, unsigned sample)
{
    if (c->used == 2) {
        ++c->lost;
        return;
    }
    c->slots[c->write] = sample;
    c->write ^= 1u;
    ++c->used;
}

static bool consume(Capture *c, unsigned *out)
{
    if (c->used == 0) return false;
    *out = c->slots[c->read];
    c->read ^= 1u;
    --c->used;
    return true;
}

int main(void)
{
    Capture c = {0};
    unsigned value;
    complete(&c, 10);
    complete(&c, 20);
    complete(&c, 30);
    if (consume(&c, &value)) printf("%u ", value);
    complete(&c, 40);
    while (consume(&c, &value)) printf("%u ", value);
    printf("lost=%u\n", c.lost);
    return 0;
}

主机运行 ​

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

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

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

主机输出与手推
text
10 20 40 lost=1

两个槽位收到 10、20,30 遇满被丢弃。消费 10 腾出空间,40 写入,随后依序读到 20、40。

练习 ​

写出在真实 DMA 启动前必须预留槽位的原因,并区分填充中与可读两个状态。

验证记录 ​

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

上一课 33 · 跟读目录 · 下一课 35