基本用法就是根据自定义的数据类型,使用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
}
}