MemPool.c 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  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. {
  15. mpid_MemPool = osMemoryPoolNew(MEMPOOL_OBJECTS,sizeof(MEM_BLOCK_t), NULL);
  16. if (mpid_MemPool == NULL) {
  17. ; // MemPool object not created, handle failure
  18. }
  19. tid_Thread_MemPool = osThreadNew (Thread_MemPool,NULL , NULL);
  20. if (tid_Thread_MemPool == NULL) {
  21. return(-1);
  22. }
  23. return(0);
  24. }
  25. void Thread_MemPool (void *argument)
  26. {
  27. osStatus_t status;
  28. MEM_BLOCK_t *pMem = 0;
  29. while (1) {
  30. ; // Insert thread code here...
  31. pMem = (MEM_BLOCK_t *)osMemoryPoolAlloc (mpid_MemPool, NULL); // get Mem Block
  32. if (pMem) { // Mem Block was available
  33. pMem->Buf[0] = 0x55; // do some work...
  34. pMem->Idx = 0;
  35. status = osMemoryPoolFree (mpid_MemPool, pMem); // free mem block
  36. switch (status) {
  37. case osOK:
  38. break;
  39. case osErrorParameter:
  40. break;
  41. case osErrorNoMemory:
  42. break;
  43. default:
  44. break;
  45. }
  46. }
  47. osThreadYield (); // suspend thread
  48. }
  49. }