Should idle thread be invoked before main?



I found that idle thread is executed before main thread and I am not sure if it is by design or it is by coincidence or maybe it is purely my setup problem.

What I did is adding 2 lines to idle thread entry point at the beginning of while(true) loop:
    extern volatile uint32_t idle_entry;

And as first lines of main I have following code:
    if (idle_entry > 0) {
        printk("idle_entry: %u", idle_entry);
The output is:
idle_entry: 2

Using different PM options and disabling PM does not change output.

Is it expected behavior?
For me it seems to be somehow nonintuitive if lowest priority thread gains control before threads with higher priorities.

BTW> Zephyr code is as it is for today (449c37808a68824faa93b77fe24f39f05e9a9939), SDK 0.13.1 and target is STM32WB55.


Andy Ross

In a technical sense yes: on a SMP system the extra CPUs will likely reach idle (each has its own idle thread obviously) before system initialization is complete and the application main() function is entered.  But that's not your platform.

Absent that, it's not architecturally possible: the main thread (which will eventually enter the main() function) is the first thread created and switched into during system initialization, by construction.  Idle can only run once it blocks.

So if I had to guess, you have a initialization function for some driver or subsystem doing a sleep.  That's not not illegal, but it's kind of weird and we should fix that if it's in-tree.



Thanks Andy, good clue.

I found that this is caused by the Bluetooth subsystem - if CONFIG_BT is enabled then I can observe described behavior (tested on blinky sample).
I will report this as issue and allow Zephyr developers to "offically" decide if it is valid behavior.