MemPool.c 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. #include "cmsis_os.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 const *argument); // thread function
  11. osThreadId tid_Thread_MemPool; // thread id
  12. osThreadDef (Thread_MemPool, osPriorityNormal, 1, 0); // thread object
  13. osPoolId mpid_MemPool; // memory pool id
  14. osPoolDef (MemPool, MEMPOOL_OBJECTS, MEM_BLOCK_t); // memory pool object
  15. int Init_MemPool (void) {
  16. mpid_MemPool = osPoolCreate (osPool (MemPool)); // create Mem Pool
  17. if (!mpid_MemPool) {
  18. ; // MemPool object not created, handle failure
  19. }
  20. tid_Thread_MemPool = osThreadCreate (osThread(Thread_MemPool), NULL);
  21. if (!tid_Thread_MemPool) return(-1);
  22. return(0);
  23. }
  24. void Thread_MemPool (void const *argument) {
  25. osStatus status;
  26. MEM_BLOCK_t *pMem = 0;
  27. while (1) {
  28. ; // Insert thread code here...
  29. pMem = (MEM_BLOCK_t *)osPoolCAlloc (mpid_MemPool); // get Mem Block
  30. if (pMem) { // Mem Block was available
  31. pMem->Buf[0] = 0x55; // do some work...
  32. pMem->Idx = 0;
  33. status = osPoolFree (mpid_MemPool, pMem); // free mem block
  34. switch (status) {
  35. case osOK:
  36. break;
  37. case osErrorParameter:
  38. break;
  39. case osErrorValue:
  40. break;
  41. default:
  42. break;
  43. }
  44. }
  45. osThreadYield (); // suspend thread
  46. }
  47. }