FreeRtos cmsis_os2中内存池Memory Pool的使用方法

 基本用法就是根据自定义的数据类型,使用osMemoryPoolNew函数定义一定数量的数据块,osMemoryPoolAlloc函数进行实时分配,osMemoryPoolFree函数进行释放。官方称比动态分配的方法快很多,具体效果我暂时还没有测试。

#include "cmsis_os2.h"// CMSIS RTOS header file
/*----------------------------------------------------------------------------
*      Memory Pool creation & usage
*---------------------------------------------------------------------------*/
#define MEMPOOL_OBJECTS 16                      // number of Memory Pool Objects
typedef struct{// 定义数据块
    uint8_t Buf[32];
    uint8_t Idx;
} MEM_BLOCK_t;
osMemoryPoolId_t mpid_MemPool;// memory pool id
osThreadId_t tid_Thread_MemPool;// thread id
void Thread_MemPool (void*argument);// thread function

int Init_MemPool (void) {
    mpid_MemPool =osMemoryPoolNew(MEMPOOL_OBJECTS,MEM_BLOCK_t, NULL);//定义内存池
    if(mpid_MemPool == NULL) {
    ;// MemPool object not created, handle failure
    }
    tid_Thread_MemPool =osThreadNew(Thread_MemPool, NULL, NULL);
    if(tid_Thread_MemPool == NULL) {
            return(-1);
        }
    return(0);
}
//开启一个线程,在这个线程中使用上面定义的内存池mpid_MemPool。
void Thread_MemPool (void*argument) {
    MEM_BLOCK_t *pMem; //数据块类型指针,指向即将被分配出来的内存池。
    osStatus_t status;
    while(1) {
        ;// Insert thread code here...
        pMem = (MEM_BLOCK_t *)osMemoryPoolAlloc(mpid_MemPool, 0U);// 创建一个内存池
        if(pMem != NULL) {// 内存池可用
            pMem->Buf[0] = 0x55U;// 干些什么...
            pMem->Idx    = 0U;
            status =osMemoryPoolFree(mpid_MemPool, pMem);// 释放内存池
                switch(status)  {
                    case    osOK:
                    break;
                    case    osErrorParameter:
                    break;
                    case    osErrorNoMemory:
                    break;
                    default:
                    break;
                }
        }
    osThreadYield();// suspend thread
    }
}

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值