Committer:
PA
Date:
Thu Jun 21 14:04:44 2012 +0000
Revision:
0:7ae810ca8a42

        

Who changed what in which revision?

UserRevisionLine numberNew contents of line
PA 0:7ae810ca8a42 1 /* Copyright (c) 2012 mbed.org */
PA 0:7ae810ca8a42 2 #ifndef MEMORYPOOL_H
PA 0:7ae810ca8a42 3 #define MEMORYPOOL_H
PA 0:7ae810ca8a42 4
PA 0:7ae810ca8a42 5 #include <stdint.h>
PA 0:7ae810ca8a42 6 #include <string.h>
PA 0:7ae810ca8a42 7
PA 0:7ae810ca8a42 8 #include "cmsis_os.h"
PA 0:7ae810ca8a42 9
PA 0:7ae810ca8a42 10 namespace rtos {
PA 0:7ae810ca8a42 11
PA 0:7ae810ca8a42 12 /*! Define and manage fixed-size memory pools of objects of a given type.
PA 0:7ae810ca8a42 13 \tparam T data type of a single object (element).
PA 0:7ae810ca8a42 14 \tparam queue_sz maximum number of objects (elements) in the memory pool.
PA 0:7ae810ca8a42 15 */
PA 0:7ae810ca8a42 16 template<typename T, uint32_t pool_sz>
PA 0:7ae810ca8a42 17 class MemoryPool {
PA 0:7ae810ca8a42 18 public:
PA 0:7ae810ca8a42 19 /*! Create and Initialize a memory pool. */
PA 0:7ae810ca8a42 20 MemoryPool() {
PA 0:7ae810ca8a42 21 #ifdef CMSIS_OS_RTX
PA 0:7ae810ca8a42 22 memset(_pool_m, 0, sizeof(_pool_m));
PA 0:7ae810ca8a42 23 _pool_def.pool = _pool_m;
PA 0:7ae810ca8a42 24
PA 0:7ae810ca8a42 25 _pool_def.pool_sz = pool_sz;
PA 0:7ae810ca8a42 26 _pool_def.item_sz = sizeof(T);
PA 0:7ae810ca8a42 27 #endif
PA 0:7ae810ca8a42 28 _pool_id = osPoolCreate(&_pool_def);
PA 0:7ae810ca8a42 29 }
PA 0:7ae810ca8a42 30
PA 0:7ae810ca8a42 31 /*! Allocate a memory block of type T from a memory pool.
PA 0:7ae810ca8a42 32 \return address of the allocated memory block or NULL in case of no memory available.
PA 0:7ae810ca8a42 33 */
PA 0:7ae810ca8a42 34 T* alloc(void) {
PA 0:7ae810ca8a42 35 return (T*)osPoolAlloc(_pool_id);
PA 0:7ae810ca8a42 36 }
PA 0:7ae810ca8a42 37
PA 0:7ae810ca8a42 38 /*! Allocate a memory block of type T from a memory pool and set memory block to zero.
PA 0:7ae810ca8a42 39 \return address of the allocated memory block or NULL in case of no memory available.
PA 0:7ae810ca8a42 40 */
PA 0:7ae810ca8a42 41 T* calloc(void) {
PA 0:7ae810ca8a42 42 return (T*)osPoolCAlloc(_pool_id);
PA 0:7ae810ca8a42 43 }
PA 0:7ae810ca8a42 44
PA 0:7ae810ca8a42 45 /*! Return an allocated memory block back to a specific memory pool.
PA 0:7ae810ca8a42 46 \param address of the allocated memory block that is returned to the memory pool.
PA 0:7ae810ca8a42 47 \return status code that indicates the execution status of the function.
PA 0:7ae810ca8a42 48 */
PA 0:7ae810ca8a42 49 osStatus free(T *block) {
PA 0:7ae810ca8a42 50 return osPoolFree(_pool_id, (void*)block);
PA 0:7ae810ca8a42 51 }
PA 0:7ae810ca8a42 52
PA 0:7ae810ca8a42 53 private:
PA 0:7ae810ca8a42 54 osPoolId _pool_id;
PA 0:7ae810ca8a42 55 osPoolDef_t _pool_def;
PA 0:7ae810ca8a42 56 #ifdef CMSIS_OS_RTX
PA 0:7ae810ca8a42 57 uint32_t _pool_m[3+((sizeof(T)+3)/4)*(pool_sz)];
PA 0:7ae810ca8a42 58 #endif
PA 0:7ae810ca8a42 59 };
PA 0:7ae810ca8a42 60
PA 0:7ae810ca8a42 61 }
PA 0:7ae810ca8a42 62 #endif