Skip to content

31 固定块内存池 · 耗尽与归还 ​

每个槽位能容纳一个对象。获取和归还按槽位管理,使用方在归还后放弃该槽位。

源码 ​

main.c ​

下载 main.c

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

enum { SLOTS = 2 };
typedef struct {
    uint8_t data[SLOTS][16];
    bool used[SLOTS];
} Pool;

static int acquire(Pool *p)
{
    for (int i = 0; i < SLOTS; ++i) {
        if (!p->used[i]) {
            p->used[i] = true;
            return i;
        }
    }
    return -1;
}

static void release(Pool *p, int id)
{
    if (id >= 0 && id < SLOTS) p->used[id] = false;
}

int main(void)
{
    Pool p = {0};
    int a = acquire(&p);
    int b = acquire(&p);
    int c = acquire(&p);
    p.data[a][0] = 42;
    release(&p, a);
    printf("%d %d %d %d\n", a, b, c, acquire(&p));
    return 0;
}

主机运行 ​

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

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

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

主机输出与手推
text
0 1 -1 0

前两次取到 0、1,池满返回 -1。归还 0 后再次取到 0。

练习 ​

让 release 返回布尔值,区分重复归还和成功归还。

关联模板 ​

FreeRTOS 指针队列与静态缓冲池

验证记录 ​

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

上一课 30 · 跟读目录 · 下一课 32