Mistake on this page?
Report an issue in GitHub or email us

MemoryPool

MemoryPool class hierarchy

You can use the MemoryPool class to define and manage fixed-size memory pools. You can allocate memory blocks of fixed size from the pool using the alloc or calloc method, which returns a pointer to the block of memory or NULL if there is no space available in the pool. It's the user's responsibility to initialize the objects placed in blocks. The calloc function sets the block of memory to zeros before returning the pointer of the block to the caller.

MemoryPool class reference

Public Member Functions
 MemoryPool ()
 ~MemoryPool ()
T * alloc (void)
T * calloc (void)
osStatus free (T *block)

MemoryPool example

MemoryPool<message_t, 16> mpool;

message_t *message = mpool.alloc();

mpool.free(message);

Queue and MemoryPool example

This example shows Queue and MemoryPool managing measurements.

#include "mbed.h"

typedef struct {
    float    voltage;   /* AD result of measured voltage */
    float    current;   /* AD result of measured current */
    uint32_t counter;   /* A counter value               */
} message_t;

MemoryPool<message_t, 16> mpool;
Queue<message_t, 16> queue;
Thread thread;

/* Send Thread */
void send_thread (void) {
    uint32_t i = 0;
    while (true) {
        i++; // fake data update
        message_t *message = mpool.alloc();
        message->voltage = (i * 0.1) * 33; 
        message->current = (i * 0.1) * 11;
        message->counter = i;
        queue.put(message);
        wait(1);
    }
}

int main (void) {
    thread.start(callback(send_thread));
    
    while (true) {
        osEvent evt = queue.get();
        if (evt.status == osEventMessage) {
            message_t *message = (message_t*)evt.value.p;
            printf("\nVoltage: %.2f V\n\r"   , message->voltage);
            printf("Current: %.2f A\n\r"     , message->current);
            printf("Number of cycles: %u\n\r", message->counter);
            
            mpool.free(message);
        }
    }
}

Important Information for this Arm website

This site uses cookies to store information on your computer. By continuing to use our site, you consent to our cookies. If you are not happy with the use of these cookies, please review our Cookie Policy to learn how they can be disabled. By disabling cookies, some features of the site will not work.