cancel
Showing results for 
Search instead for 
Did you mean: 

How does tx_byte_allocate() work in ThreadX?

mahirmahota
Associate III

I just had a quick question to clarify my understanding of how byte allocation works for thread stacks in the ThreadX RTOS. I've seen the official examples use a byte pool and then allocate bytes from that pool before creating a new thread. However, in other places I've seen something as follows where the bytes are allocated statically:

 

/* Private variables ---------------------------------------------------------*/
uint8_t thread_stack[TX_THREAD_STACK_SIZE];
TX_THREAD thread;

/* Private function prototypes -----------------------------------------------*/
VOID thread_entry(ULONG thread_input);

/**
  * @brief  Application ThreadX Initialization.
  *  memory_ptr: memory pointer
  * @retval int
  */
UINT App_ThreadX_Init(VOID *memory_ptr)
{
  UINT ret = TX_SUCCESS;
  TX_BYTE_POOL *byte_pool = (TX_BYTE_POOL*)memory_ptr;
  (void)byte_pool;

  tx_thread_create(&thread, "thread", thread_entry, 0,
                   thread_stack, TX_THREAD_STACK_SIZE, 15, 15, 
                   TX_NO_TIME_SLICE, TX_AUTO_START);

  return ret;
}

Are these two methods of creating the thread stack interchangeable or should one be preferred over the other? The overall byte pool is allocated statically in my application but is still passed through the tx_byte_pool_create() function which I don't understand either since I thought the byte creation functions are meant for dynamic allocation instead. I'd be grateful if you could clear my confusion!

1 REPLY 1
Saket_Om
ST Employee

Hello @mahirmahota 

For most embedded applications where the number of threads is fixed and known at compile time, static allocation of thread stacks is generally preferred. This approach offers greater simplicity, predictability, and reliability, as it avoids potential issues with memory fragmentation and allocation failures at runtime. On the other hand, dynamic allocation using a byte pool is more suitable if your application requires creating and destroying threads dynamically. In summary, choose static allocation for fixed, predictable thread usage, and opt for dynamic allocation when flexibility and runtime thread management are needed.

To give better visibility on the answered topics, please click on "Accept as Solution" on the reply which solved your issue or answered your question.
Saket_Om