Skip to content
systemcoding.dev
RTOS

Use ThreadX Byte and Block Memory Pools

Allocate memory in ThreadX with byte pools and fixed-size block pools, using tx_byte_allocate and tx_block_allocate, and choose by fragmentation and timing.

6 min read
Summarize in AI
Flat illustration of RTOS tasks taking turns on a timeline, with the C, Espressif and Arm logos.

ThreadX does not use the C library's malloc() for its own objects, and it discourages it for yours. Instead it offers two kinds of memory pool: byte pools, which hand out variable-sized pieces from a region, and block pools, which hand out fixed-size blocks from a region. They are different tools with different guarantees, and a ThreadX program usually uses both. This post shows how each works, what each costs and how to choose, on ThreadX 6.4, following the ThreadX user guide. The call names are the ones from the tx_api.h header.

Why pools instead of malloc

Embedded programs have two problems with general-purpose allocation. It is unpredictable, since the time to find a free chunk depends on the state of the heap. And it fragments: after many allocations and frees of varying sizes, memory is available in total but not in one piece, and a request fails. A pool confines the problem to a region you choose, with behavior you can reason about, and ThreadX adds a feature the C library lacks: a thread can suspend on a pool until memory becomes available, with a timeout, instead of getting an immediate failure.

Byte pools

A byte pool is a region from which you allocate pieces of any size. You create it with a name, a start address and a size:

c
#define POOL_SIZE 4096

static TX_BYTE_POOL app_pool;
static UCHAR pool_memory[POOL_SIZE];

tx_byte_pool_create(&app_pool, "app pool", pool_memory, POOL_SIZE);

Allocation takes the pool, a pointer variable, a size and a wait option, and gives back a pointer:

c
VOID *buffer;
UINT status = tx_byte_allocate(&app_pool, &buffer, 200, TX_NO_WAIT);

if (status == TX_SUCCESS) {
	/* use buffer */
	tx_byte_release(buffer);
}

tx_byte_release() returns the piece to the pool, and it needs only the pointer, since the pool stores a small header before each allocation that records its owner and size. That header is overhead: each allocation costs a few extra bytes beyond what you asked, and ThreadX rounds sizes up to a multiple of the alignment. A pool of 4096 bytes will therefore not hold 20 allocations of 200 bytes.

The algorithm is first-fit with a search pointer: the allocator scans from where it last stopped for the first free area that is large enough, splits it and merges adjacent free areas as it goes. It is fast on average and its worst-case time grows with the number of fragments, so it is not constant time. Fragmentation is real: allocate and release pieces of many sizes over a long time and the pool can hold plenty of free bytes but no contiguous region large enough. ThreadX defragments lazily during an allocation search, merging neighbors, but it cannot move allocated pieces.

If memory is short, a thread can wait. Pass a tick count or TX_WAIT_FOREVER instead of TX_NO_WAIT, and the thread suspends until another thread releases enough memory or the timeout expires. This is the feature that makes a byte pool useful for requests that can wait, and a hazard for threads that must not block, such as ones feeding a watchdog.

The size of a byte pool is the total including all overhead, and the pool itself has a small header. Use tx_byte_pool_info_get() to read the number of fragments and the available bytes at run time, which is how you tell whether a pool is healthy in a long soak test.

Block pools

A block pool divides a region into equal blocks. You give the block size and the region, and the pool creates as many blocks as fit:

c
#define BLOCK_SIZE   64
#define BLOCK_COUNT  16

static TX_BLOCK_POOL packet_pool;
static UCHAR packet_memory[BLOCK_COUNT * (BLOCK_SIZE + sizeof(void *))];

tx_block_pool_create(&packet_pool, "packets", BLOCK_SIZE,
		     packet_memory, sizeof(packet_memory));

Each block carries a pointer's worth of overhead, which the kernel uses to link free blocks, so the region must hold BLOCK_SIZE + sizeof(void *) per block. The expression above reserves exactly that for 16 blocks. A smaller region gives fewer blocks, and you can read the real count with tx_block_pool_info_get().

c
VOID *pkt;

if (tx_block_allocate(&packet_pool, &pkt, TX_NO_WAIT) == TX_SUCCESS) {
	/* fill the packet */
	tx_block_release(pkt);
}

Allocation and release take constant time: the pool keeps a linked list of free blocks and removes the head or pushes onto it. There is no search, no splitting and no merging, so there is no fragmentation inside the pool, and the time is the same every call. That makes block pools the right choice for anything on a time-critical path, such as network buffers filled in an interrupt handler, which may call tx_block_allocate() with TX_NO_WAIT.

The limitation is the single size. If you need blocks of 64 and of 512 bytes, make two pools. A request smaller than the block wastes the rest, and a request larger cannot be satisfied. Choose the block size from the largest object that uses the pool, and keep pools per object type, which also isolates one type's exhaustion from another's.

A program that uses both

A common pattern is to use a block pool for the fixed-size objects that flow between threads and a byte pool for objects created at start-up, such as thread stacks. In ThreadX itself, the first unused memory pointer given to tx_application_define() is typically used to create the first byte pool, and the threads' stacks are then allocated from it:

c
static TX_BYTE_POOL system_pool;

void tx_application_define(void *first_unused_memory)
{
	VOID *stack;

	tx_byte_pool_create(&system_pool, "system", first_unused_memory, 8192);

	tx_byte_allocate(&system_pool, &stack, 1024, TX_NO_WAIT);
	tx_thread_create(&worker, "worker", worker_entry, 0,
			 stack, 1024, 8, 8, TX_NO_TIME_SLICE, TX_AUTO_START);

	tx_block_pool_create(&packet_pool, "packets", 64,
			     packet_memory, sizeof(packet_memory));
}

The 8192 is a number you choose and must not exceed the memory your linker script leaves after the program. first_unused_memory is the start of RAM that the kernel has not claimed, which the port computes from a linker symbol; check your port's tx_initialize_low_level source for how it does so, since getting the end of RAM wrong is a common cause of start-up corruption.

If the pool allocations all happen at start-up and nothing is ever freed, a byte pool is a bump allocator with checking. That is a good pattern for a deterministic system: allocate everything at boot, allocate nothing afterward, and the fragmentation question never arises.

Choosing

NeedUse
Fixed-size objects, frequent alloc and freeBlock pool
Allocation from an interrupt handlerBlock pool with TX_NO_WAIT
Variable sizes, rare alloc and freeByte pool
Stacks and objects created once at start-upByte pool
Waiting for memory with a timeoutEither; both support suspension
Predictable worst-case timeBlock pool

Pitfalls

Releasing a pointer to the wrong pool corrupts both: ThreadX stores the owning pool in the header, so release is safe for pointers from the right pool, but passing a pointer that did not come from a pool is undefined. Writing past the end of an allocation corrupts the next header, which shows up later as a failure in an unrelated allocation. A block pool whose region is smaller than expected silently has fewer blocks. A byte pool whose memory is shared with another use overlaps without any error. Allocations that are never released leak until the pool is empty, and a thread suspended forever on an empty pool looks like a hang, so use timeouts on production allocations.

Share

Keep reading

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.