C语言-简单的缓冲池(Buffer Pool)的源码示例

概述

用C语言实现,缓冲池用于管理一组固定大小的缓冲区,并提供分配和释放缓冲区的功能。

cpp 复制代码
#include <stdio.h>
#include <stdint.h>
#include <stdbool.h>

#define BUFFER_SIZE 64
#define POOL_SIZE   10

// 定义缓冲区结构体
typedef struct {
    uint8_t data[BUFFER_SIZE];
    bool inUse;
} Buffer;

// 定义缓冲池结构体
typedef struct {
    Buffer buffers[POOL_SIZE];
} BufferPool;

// 初始化缓冲池
void initBufferPool(BufferPool* pool) 
{
    for (int i = 0; i < POOL_SIZE; ++i) {
        pool->buffers[i].inUse = false;
    }
}

// 分配缓冲区
uint8_t* allocateBuffer(BufferPool* pool) 
{
    for (int i = 0; i < POOL_SIZE; ++i) {
        if (!pool->buffers[i].inUse) {
            pool->buffers[i].inUse = true;
            return pool->buffers[i].data;
        }
    }
    // 没有可用的缓冲区
    return NULL;
}

// 释放缓冲区
void freeBuffer(BufferPool* pool, uint8_t* buffer) 
{
    for (int i = 0; i < POOL_SIZE; ++i) {
        if (pool->buffers[i].data == buffer) {
            pool->buffers[i].inUse = false;
            return;
        }
    }
    // 找不到对应的缓冲区
    printf("Failed to free buffer: Buffer not found\n");
}

int main(void)
{
    BufferPool pool;
    initBufferPool(&pool);

    // 分配缓冲区
    uint8_t* buffer1 = allocateBuffer(&pool);
    if (buffer1 != NULL) {
        // 使用缓冲区
        // ...
        // 释放缓冲区
        freeBuffer(&pool, buffer1);
    }

    // 分配另一个缓冲区
    uint8_t* buffer2 = allocateBuffer(&pool);
    if (buffer2 != NULL) {
        // 使用缓冲区
        // ...
        // 释放缓冲区
        freeBuffer(&pool, buffer2);
    }

    return 0;
}
相关推荐
怀旧,5 分钟前
【数据结构】6. 时间与空间复杂度
java·数据结构·算法
积极向上的向日葵18 分钟前
有效的括号题解
数据结构·算法·
GIS小天24 分钟前
AI+预测3D新模型百十个定位预测+胆码预测+去和尾2025年6月7日第101弹
人工智能·算法·机器学习·彩票
_Itachi__1 小时前
LeetCode 热题 100 74. 搜索二维矩阵
算法·leetcode·矩阵
不忘不弃1 小时前
计算矩阵A和B的乘积
线性代数·算法·矩阵
不爱写代码的玉子1 小时前
HALCON透视矩阵
人工智能·深度学习·线性代数·算法·计算机视觉·矩阵·c#
Java 技术轻分享1 小时前
《树数据结构解析:核心概念、类型特性、应用场景及选择策略》
数据结构·算法·二叉树··都差速
芜湖xin1 小时前
【题解-洛谷】P1706 全排列问题
算法·dfs
chao_7892 小时前
链表题解——两两交换链表中的节点【LeetCode】
数据结构·python·leetcode·链表
学习噢学个屁2 小时前
基于STM32语音识别柔光台灯
c语言·stm32·单片机·嵌入式硬件·语音识别