A thread is the basic unit of runnable code. The vast majority of firmware code will run in threads – whether it’s a user-defined thread, a thread created by the RTOS (for example a system workqueue thread), a thread created by an RTOS subsystem (for example a logger module), or a thread created by a library (for example the AT Monitor library).
A thread has the following items:
k_thread.
For each thread, there will be an instance of a thread control block within the RTOS that keeps track of a thread’s information, specifically its metadata.K_NO_WAIT
which is simply a start delay of 0. Or we can specify an optional start delay.Threads are created using either the K_THREAD_DEFINE()
macro or the k_thread_create()
function. In both cases, a stack needs to be allocated statically (dynamic threads are not supported in Zephyr RTOS as of v3.4.0). The K_THREAD_DEFINE()
macro manages the stack allocation itself, and the desired stack size is passed as a parameter to the same macro. Conversely, if you use the k_thread_create()
function, you must allocate a stack using the K_THREAD_STACK_DEFINE()
macro in advance.
Recall from Lesson 7 – Multithreaded applications and Lesson 8 – Thread synchronization in the nRF Connect SDK Fundamentals course, when creating a thread, you can start it immediately or after specifying a certain delay. Once the thread is started, it is placed in the queue of ready threads (ready queue).
As was covered in the fundamentals course, when creating a thread, you can start it immediately or after specifying a certain delay. Once the thread is started, it is placed in the queue of ready threads (ready queue).
There is also the option to create a thread with the delay set to K_FOREVER, which effectively makes the thread inactive. To activate, call k_thread_start()
, which will add the thread to the queue of ready threads (ready queue).
Ready queue: The queue of threads that has the state Ready. The scheduler only cares about the threads in the ready queue when deciding which one should be the current Running thread.
If the scheduler picks up the thread for execution, its state transitions to Running. Scheduling policies are covered in the next topic, Scheduling in-depth. The thread will stay Running until:
k_sleep()
or its derivatives.k_thread_suspend()
.k_yield()
to give up the CPU, and putting itself at the end of the ready queue.k_thread_abort()
function.More details on threads can be found on the Threads page of the nRF Connect SDK documentation.