MemPool.c 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. #include "cmsis_os2.h" // CMSIS RTOS header file
  2. /*----------------------------------------------------------------------------
  3. * Memory Pool creation & usage
  4. *---------------------------------------------------------------------------*/
  5. #define MEMPOOL_OBJECTS 16 // number of Memory Pool Objects
  6. typedef struct { // object data type
  7. uint8_t Buf[32];
  8. uint8_t Idx;
  9. } MEM_BLOCK_t;
  10. void *Thread_MemPool (void *argument); // thread function
  11. osThreadId_t tid_Thread_MemPool; // thread id
  12. osMemoryPoolId_t mpid_MemPool; // memory pool id
  13. int Init_MemPool (void) {
  14. mpid_MemPool = osMemoryPoolNew(MEMPOOL_OBJECTS,sizeof(MEM_BLOCK_t), NULL);
  15. if (!mpid_MemPool) {
  16. ; // MemPool object not created, handle failure
  17. }
  18. tid_Thread_MemPool = osThreadNew (Thread_MemPool,NULL , NULL);
  19. if (!tid_Thread_MemPool) return(-1);
  20. return(0);
  21. }
  22. void *Thread_MemPool (void *argument) {
  23. osStatus_t status;
  24. MEM_BLOCK_t *pMem = 0;
  25. while (1) {
  26. ; // Insert thread code here...
  27. pMem = (MEM_BLOCK_t *)osMemoryPoolAlloc (mpid_MemPool, NULL); // get Mem Block
  28. if (pMem) { // Mem Block was available
  29. pMem->Buf[0] = 0x55; // do some work...
  30. pMem->Idx = 0;
  31. status = osMemoryPoolFree (mpid_MemPool, pMem); // free mem block
  32. switch (status) {
  33. case osOK:
  34. break;
  35. case osErrorParameter:
  36. break;
  37. case osErrorNoMemory:
  38. break;
  39. default:
  40. break;
  41. }
  42. }
  43. osThreadYield (); // suspend thread
  44. }
  45. }