Create ThreadX Threads With tx_thread_create on STM32
Start two ThreadX threads on an STM32 with tx_kernel_enter, tx_application_define and tx_thread_create, and learn priorities, stacks, time slices and sleep.

A thread is the unit of work in ThreadX: a function with its own stack and priority, scheduled by the kernel. This post creates two threads on an STM32 microcontroller, one that blinks an LED and one that counts, explains each argument of tx_thread_create() and shows what the scheduler does with them. It assumes you have a ThreadX port for your Cortex-M part, which an STM32Cube package or the upstream repository at github.com/eclipse-threadx/threadx provides, as described in the ThreadX user guide. The code uses ThreadX 6.4 types and calls; the hardware calls are from the STM32 HAL for the LED.
The program skeleton
Every ThreadX program has the same shape. main() prepares the hardware and then calls tx_kernel_enter(), which starts the kernel and does not return. The kernel calls your tx_application_define() once, before the scheduler runs, so that you can create the system's objects:
#include "tx_api.h"
#include "stm32f4xx_hal.h"
#define STACK_SIZE 1024
static TX_THREAD blink_thread;
static TX_THREAD count_thread;
static ULONG blink_stack[STACK_SIZE / sizeof(ULONG)];
static ULONG count_stack[STACK_SIZE / sizeof(ULONG)];
static volatile ULONG counter;
int main(void)
{
HAL_Init();
SystemClock_Config();
MX_GPIO_Init();
tx_kernel_enter();
return 0;
}HAL_Init(), SystemClock_Config() and MX_GPIO_Init() are the usual generated STM32 functions; they set up the clock tree and the LED pin. The two threads need a control block, a TX_THREAD structure that the kernel fills, and a stack, which you provide. Stacks are arrays of ULONG so they are aligned to four bytes, and they are static so they live for the life of the program. Keep the type ULONG in mind: ThreadX defines ULONG as a 32-bit unsigned value, and UINT as an unsigned int.
Create the threads
The two thread functions take one ULONG argument, the value passed at creation, and normally never return:
static void blink_entry(ULONG input)
{
(void)input;
while (1) {
HAL_GPIO_TogglePin(GPIOD, GPIO_PIN_12);
tx_thread_sleep(50);
}
}
static void count_entry(ULONG input)
{
while (1) {
counter += input;
tx_thread_sleep(100);
}
}
void tx_application_define(void *first_unused_memory)
{
(void)first_unused_memory;
tx_thread_create(&blink_thread, "blink", blink_entry, 0,
blink_stack, sizeof(blink_stack),
5, 5, TX_NO_TIME_SLICE, TX_AUTO_START);
tx_thread_create(&count_thread, "count", count_entry, 1,
count_stack, sizeof(count_stack),
10, 10, TX_NO_TIME_SLICE, TX_AUTO_START);
}The call has ten arguments, which is a lot for a first look, so take them one at a time:
&blink_thread: the control block."blink": a name, used by debuggers and by some kernel services; the string must stay valid, and a literal does.blink_entry: the function to run.0: the value passed to the function as its argument.blink_stack: the address of the stack memory.sizeof(blink_stack): the stack size in bytes.5: the priority. In ThreadX a lower number is more urgent, from 0 toTX_MAX_PRIORITIES - 1, and the default maximum is 32 priorities.5: the preemption threshold, a ThreadX feature. Set it equal to the priority for ordinary behavior, which means any more urgent thread can preempt this one. A lower number than the priority disables preemption by a range of priorities, a tool for reducing context switches that you can ignore at first.TX_NO_TIME_SLICE: how many ticks the thread may run before yielding to a ready thread of the same priority. Zero, spelledTX_NO_TIME_SLICE, means it runs until it blocks or is preempted.TX_AUTO_START: start the thread immediately. The alternative,TX_DONT_START, creates it suspended until you calltx_thread_resume().
The call returns TX_SUCCESS when it works, and an error code otherwise, such as TX_SIZE_ERROR for a stack that is too small or TX_PRIORITY_ERROR for a priority out of range. Check the return value while you learn; an ignored failure means the thread silently never runs.
What happens when it runs
After tx_application_define() returns, the scheduler picks the ready thread with the highest priority. Both threads are ready; blink has priority 5, more urgent than count at 10, so it runs first. It toggles the pin and calls tx_thread_sleep(50), which suspends the thread for 50 timer ticks. The default tick rate is 100 ticks per second, set by TX_TIMER_TICKS_PER_SECOND, so the sleep is half a second, and the LED toggles every half second. While blink sleeps, the scheduler runs count, which adds to counter and sleeps for a second. When the CPU has nothing else to do, the kernel runs its idle loop and, if the port supports it, waits for an interrupt.
Because blink is more urgent, when its sleep ends it preempts count immediately, even in the middle of count's work. This is the heart of a preemptive RTOS, and it is why shared variables need protection. Here counter is only written by one thread, so it is safe to read from elsewhere as a diagnostic.
You can see the behavior on a logic analyzer on the LED pin, or by watching counter in the debugger: it rises by one every second. The numbers follow from the tick rate; check your port's TX_TIMER_TICKS_PER_SECOND if the timing differs.
Stack size
The 1024 bytes in the example are a starting point and not a rule. Each thread's stack must hold its local variables, the frames of every function it calls, and the register context saved when it is preempted, which on a Cortex-M4 with floating point can be over a hundred bytes. ThreadX can fill stacks with a pattern at creation, and tx_thread_stack_error_notify() or the stack-checking build option helps find overflows; the thread's control block also records its high-water mark in the field tx_thread_stack_highest_ptr. If a thread crashes only in some code paths, suspect its stack first.
Time slicing
If two threads share a priority, ThreadX can alternate them. Pass a number of ticks, say 5, instead of TX_NO_TIME_SLICE, and each of the two gets five ticks before the other runs, as long as both are ready. Without it, the thread that started first runs until it blocks. Most designs avoid equal priorities for threads that do continuous work, and give each a different priority that reflects its urgency.
Common mistakes
Returning from a thread function. When a thread entry function returns, the thread enters a completed state and never runs again. Use an endless loop unless you mean it.
Forgetting the SysTick hookup. The port needs a timer interrupt to drive the tick; on Cortex-M this is SysTick, wired to
_tx_timer_interruptin the port's startup code. If you integrate ThreadX into HAL-generated code, make sure the HAL's own SysTick handler calls the ThreadX tick, or sleeps never end.Reusing a stack for two threads, or putting a stack on the stack of a function that returns.
Calling blocking ThreadX services from
main()before the kernel starts.


