1.. _threads_v2:
2
3Threads
4#######
5
6.. note::
7   There is also limited support for using :ref:`nothread`.
8
9.. contents::
10    :local:
11    :depth: 2
12
13This section describes kernel services for creating, scheduling, and deleting
14independently executable threads of instructions.
15
16A :dfn:`thread` is a kernel object that is used for application processing
17that is too lengthy or too complex to be performed by an ISR.
18
19Any number of threads can be defined by an application (limited only by
20available RAM). Each thread is referenced by a :dfn:`thread id` that is assigned
21when the thread is spawned.
22
23A thread has the following key properties:
24
25* A **stack area**, which is a region of memory used for the thread's stack.
26  The **size** of the stack area can be tailored to conform to the actual needs
27  of the thread's processing. Special macros exist to create and work with
28  stack memory regions.
29
30* A **thread control block** for private kernel bookkeeping of the thread's
31  metadata. This is an instance of type :c:struct:`k_thread`.
32
33* An **entry point function**, which is invoked when the thread is started.
34  Up to 3 **argument values** can be passed to this function.
35
36* A **scheduling priority**, which instructs the kernel's scheduler how to
37  allocate CPU time to the thread. (See :ref:`scheduling_v2`.)
38
39* A set of **thread options**, which allow the thread to receive special
40  treatment by the kernel under specific circumstances.
41  (See :ref:`thread_options_v2`.)
42
43* A **start delay**, which specifies how long the kernel should wait before
44  starting the thread.
45
46* An **execution mode**, which can either be supervisor or user mode.
47  By default, threads run in supervisor mode and allow access to
48  privileged CPU instructions, the entire memory address space, and
49  peripherals. User mode threads have a reduced set of privileges.
50  This depends on the :kconfig:option:`CONFIG_USERSPACE` option. See :ref:`usermode_api`.
51
52.. _lifecycle_v2:
53
54Lifecycle
55***********
56
57.. _spawning_thread:
58
59Thread Creation
60===============
61
62A thread must be created before it can be used. The kernel initializes
63the thread control block as well as one end of the stack portion. The remainder
64of the thread's stack is typically left uninitialized.
65
66Specifying a start delay of :c:macro:`K_NO_WAIT` instructs the kernel
67to start thread execution immediately. Alternatively, the kernel can be
68instructed to delay execution of the thread by specifying a timeout
69value -- for example, to allow device hardware used by the thread
70to become available.
71
72The kernel allows a delayed start to be canceled before the thread begins
73executing. A cancellation request has no effect if the thread has already
74started. A thread whose delayed start was successfully canceled must be
75re-spawned before it can be used.
76
77Thread Termination
78===================
79
80Once a thread is started it typically executes forever. However, a thread may
81synchronously end its execution by returning from its entry point function.
82This is known as **termination**.
83
84A thread that terminates is responsible for releasing any shared resources
85it may own (such as mutexes and dynamically allocated memory)
86prior to returning, since the kernel does *not* reclaim them automatically.
87
88In some cases a thread may want to sleep until another thread terminates.
89This can be accomplished with the :c:func:`k_thread_join` API. This
90will block the calling thread until either the timeout expires, the target
91thread self-exits, or the target thread aborts (either due to a
92:c:func:`k_thread_abort` call or triggering a fatal error).
93
94Once a thread has terminated, the kernel guarantees that no use will
95be made of the thread struct.  The memory of such a struct can then be
96re-used for any purpose, including spawning a new thread.  Note that
97the thread must be fully terminated, which presents race conditions
98where a thread's own logic signals completion which is seen by another
99thread before the kernel processing is complete.  Under normal
100circumstances, application code should use :c:func:`k_thread_join` or
101:c:func:`k_thread_abort` to synchronize on thread termination state
102and not rely on signaling from within application logic.
103
104Thread Aborting
105===============
106
107A thread may asynchronously end its execution by **aborting**. The kernel
108automatically aborts a thread if the thread triggers a fatal error condition,
109such as dereferencing a null pointer.
110
111A thread can also be aborted by another thread (or by itself)
112by calling :c:func:`k_thread_abort`. However, it is typically preferable
113to signal a thread to terminate itself gracefully, rather than aborting it.
114
115As with thread termination, the kernel does not reclaim shared resources
116owned by an aborted thread.
117
118.. note::
119    The kernel does not currently make any claims regarding an application's
120    ability to respawn a thread that aborts.
121
122Thread Suspension
123==================
124
125A thread can be prevented from executing for an indefinite period of time
126if it becomes **suspended**. The function :c:func:`k_thread_suspend`
127can be used to suspend any thread, including the calling thread.
128Suspending a thread that is already suspended has no additional effect.
129
130Once suspended, a thread cannot be scheduled until another thread calls
131:c:func:`k_thread_resume` to remove the suspension.
132
133.. note::
134   A thread can prevent itself from executing for a specified period of time
135   using :c:func:`k_sleep`. However, this is different from suspending
136   a thread since a sleeping thread becomes executable automatically when the
137   time limit is reached.
138
139.. _thread_states:
140
141Thread States
142*************
143
144A thread that has no factors that prevent its execution is deemed
145to be **ready**, and is eligible to be selected as the current thread.
146
147A thread that has one or more factors that prevent its execution
148is deemed to be **unready**, and cannot be selected as the current thread.
149
150The following factors make a thread unready:
151
152* The thread has not been started.
153* The thread is waiting for a kernel object to complete an operation.
154  (For example, the thread is taking a semaphore that is unavailable.)
155* The thread is waiting for a timeout to occur.
156* The thread has been suspended.
157* The thread has terminated or aborted.
158
159  .. image:: thread_states.svg
160     :align: center
161
162.. note::
163
164  Although the diagram above may appear to suggest that both **Ready** and
165  **Running** are distinct thread states, that is not the correct
166  interpretation. **Ready** is a thread state, and **Running** is a
167  schedule state that only applies to **Ready** threads.
168
169Thread Stack objects
170********************
171
172Every thread requires its own stack buffer for the CPU to push context.
173Depending on configuration, there are several constraints that must be
174met:
175
176- There may need to be additional memory reserved for memory management
177  structures
178- If guard-based stack overflow detection is enabled, a small write-protected
179  memory management region must immediately precede the stack buffer
180  to catch overflows.
181- If userspace is enabled, a separate fixed-size privilege elevation stack must
182  be reserved to serve as a private kernel stack for handling system calls.
183- If userspace is enabled, the thread's stack buffer must be appropriately
184  sized and aligned such that a memory protection region may be programmed
185  to exactly fit.
186
187The alignment constraints can be quite restrictive, for example some MPUs
188require their regions to be of some power of two in size, and aligned to its
189own size.
190
191Because of this, portable code can't simply pass an arbitrary character buffer
192to :c:func:`k_thread_create`. Special macros exist to instantiate stacks
193statically, prefixed with ``K_KERNEL_STACK`` and ``K_THREAD_STACK``.
194
195Additionally, stacks may be instantiated dynamically using
196:c:func:`k_thread_stack_alloc` and subsequently freed with
197:c:func:`k_thread_stack_free`.
198
199Kernel-only Stacks
200==================
201
202If it is known that a thread will never run in user mode, or the stack is
203being used for special contexts like handling interrupts, it is best to
204define stacks using the ``K_KERNEL_STACK`` macros.
205
206These stacks save memory because an MPU region will never need to be
207programmed to cover the stack buffer itself, and the kernel will not need
208to reserve additional room for the privilege elevation stack, or memory
209management data structures which only pertain to user mode threads.
210
211Attempts from user mode to use stacks declared in this way will result in
212a fatal error for the caller.
213
214If ``CONFIG_USERSPACE`` is not enabled, the set of ``K_THREAD_STACK`` macros
215have an identical effect to the ``K_KERNEL_STACK`` macros.
216
217Thread stacks
218=============
219
220If it is known that a stack will need to host user threads, or if this
221cannot be determined, define the stack with ``K_THREAD_STACK`` macros.
222This may use more memory but the stack object is suitable for hosting
223user threads.
224
225If ``CONFIG_USERSPACE`` is not enabled, the set of ``K_THREAD_STACK`` macros
226have an identical effect to the ``K_KERNEL_STACK`` macros.
227
228.. _thread_priorities:
229
230Thread Priorities
231******************
232
233A thread's priority is an integer value, and can be either negative or
234non-negative.
235Numerically lower priorities takes precedence over numerically higher values.
236For example, the scheduler gives thread A of priority 4 *higher* priority
237over thread B of priority 7; likewise thread C of priority -2 has higher
238priority than both thread A and thread B.
239
240The scheduler distinguishes between two classes of threads,
241based on each thread's priority.
242
243* A :dfn:`cooperative thread` has a negative priority value.
244  Once it becomes the current thread, a cooperative thread remains
245  the current thread until it performs an action that makes it unready.
246
247* A :dfn:`preemptible thread` has a non-negative priority value.
248  Once it becomes the current thread, a preemptible thread may be supplanted
249  at any time if a cooperative thread, or a preemptible thread of higher
250  or equal priority, becomes ready.
251
252
253A thread's initial priority value can be altered up or down after the thread
254has been started. Thus it is possible for a preemptible thread to become
255a cooperative thread, and vice versa, by changing its priority.
256
257.. note::
258    The scheduler does not make heuristic decisions to re-prioritize threads.
259    Thread priorities are set and changed only at the application's request.
260
261The kernel supports a virtually unlimited number of thread priority levels.
262The configuration options :kconfig:option:`CONFIG_NUM_COOP_PRIORITIES` and
263:kconfig:option:`CONFIG_NUM_PREEMPT_PRIORITIES` specify the number of priority
264levels for each class of thread, resulting in the following usable priority
265ranges:
266
267* cooperative threads: (-:kconfig:option:`CONFIG_NUM_COOP_PRIORITIES`) to -1
268* preemptive threads: 0 to (:kconfig:option:`CONFIG_NUM_PREEMPT_PRIORITIES` - 1)
269
270.. image:: priorities.svg
271   :align: center
272
273For example, configuring 5 cooperative priorities and 10 preemptive priorities
274results in the ranges -5 to -1 and 0 to 9, respectively.
275
276.. _metairq_priorities:
277
278Meta-IRQ Priorities
279===================
280
281When enabled (see :kconfig:option:`CONFIG_NUM_METAIRQ_PRIORITIES`), there is a special
282subclass of cooperative priorities at the highest (numerically lowest)
283end of the priority space: meta-IRQ threads.  These are scheduled
284according to their normal priority, but also have the special ability
285to preempt all other threads (and other meta-IRQ threads) at lower
286priorities, even if those threads are cooperative and/or have taken a
287scheduler lock. Meta-IRQ threads are still threads, however,
288and can still be interrupted by any hardware interrupt.
289
290This behavior makes the act of unblocking a meta-IRQ thread (by any
291means, e.g. creating it, calling k_sem_give(), etc.) into the
292equivalent of a synchronous system call when done by a lower
293priority thread, or an ARM-like "pended IRQ" when done from true
294interrupt context.  The intent is that this feature will be used to
295implement interrupt "bottom half" processing and/or "tasklet" features
296in driver subsystems.  The thread, once woken, will be guaranteed to
297run before the current CPU returns into application code.
298
299Unlike similar features in other OSes, meta-IRQ threads are true
300threads and run on their own stack (which must be allocated normally),
301not the per-CPU interrupt stack. Design work to enable the use of the
302IRQ stack on supported architectures is pending.
303
304Note that because this breaks the promise made to cooperative
305threads by the Zephyr API (namely that the OS won't schedule other
306thread until the current thread deliberately blocks), it should be
307used only with great care from application code.  These are not simply
308very high priority threads and should not be used as such.
309
310.. _thread_options_v2:
311
312Thread Options
313***************
314
315The kernel supports a small set of :dfn:`thread options` that allow a thread
316to receive special treatment under specific circumstances. The set of options
317associated with a thread are specified when the thread is spawned.
318
319A thread that does not require any thread option has an option value of zero.
320A thread that requires a thread option specifies it by name, using the
321:literal:`|` character as a separator if multiple options are needed
322(i.e. combine options using the bitwise OR operator).
323
324The following thread options are supported.
325
326:c:macro:`K_ESSENTIAL`
327    This option tags the thread as an :dfn:`essential thread`. This instructs
328    the kernel to treat the termination or aborting of the thread as a fatal
329    system error.
330
331    By default, the thread is not considered to be an essential thread.
332
333:c:macro:`K_SSE_REGS`
334    This x86-specific option indicate that the thread uses the CPU's
335    SSE registers. Also see :c:macro:`K_FP_REGS`.
336
337    By default, the kernel does not attempt to save and restore the contents
338    of these registers when scheduling the thread.
339
340:c:macro:`K_FP_REGS`
341    This option indicate that the thread uses the CPU's floating point
342    registers. This instructs the kernel to take additional steps to save
343    and restore the contents of these registers when scheduling the thread.
344    (For more information see :ref:`float_v2`.)
345
346    By default, the kernel does not attempt to save and restore the contents
347    of this register when scheduling the thread.
348
349:c:macro:`K_USER`
350    If :kconfig:option:`CONFIG_USERSPACE` is enabled, this thread will be created in
351    user mode and will have reduced privileges. See :ref:`usermode_api`. Otherwise
352    this flag does nothing.
353
354:c:macro:`K_INHERIT_PERMS`
355    If :kconfig:option:`CONFIG_USERSPACE` is enabled, this thread will inherit all
356    kernel object permissions that the parent thread had, except the parent
357    thread object.  See :ref:`usermode_api`.
358
359
360.. _custom_data_v2:
361
362Thread Custom Data
363******************
364
365Every thread has a 32-bit :dfn:`custom data` area, accessible only by
366the thread itself, and may be used by the application for any purpose
367it chooses. The default custom data value for a thread is zero.
368
369.. note::
370   Custom data support is not available to ISRs because they operate
371   within a single shared kernel interrupt handling context.
372
373By default, thread custom data support is disabled. The configuration option
374:kconfig:option:`CONFIG_THREAD_CUSTOM_DATA` can be used to enable support.
375
376The :c:func:`k_thread_custom_data_set` and
377:c:func:`k_thread_custom_data_get` functions are used to write and read
378a thread's custom data, respectively. A thread can only access its own
379custom data, and not that of another thread.
380
381The following code uses the custom data feature to record the number of times
382each thread calls a specific routine.
383
384.. note::
385    Obviously, only a single routine can use this technique,
386    since it monopolizes the use of the custom data feature.
387
388.. code-block:: c
389
390    int call_tracking_routine(void)
391    {
392        uint32_t call_count;
393
394        if (k_is_in_isr()) {
395	    /* ignore any call made by an ISR */
396        } else {
397            call_count = (uint32_t)k_thread_custom_data_get();
398            call_count++;
399            k_thread_custom_data_set((void *)call_count);
400	}
401
402        /* do rest of routine's processing */
403        ...
404    }
405
406Use thread custom data to allow a routine to access thread-specific information,
407by using the custom data as a pointer to a data structure owned by the thread.
408
409Implementation
410**************
411
412Spawning a Thread
413=================
414
415A thread is spawned by defining its stack area and its thread control block,
416and then calling :c:func:`k_thread_create`.
417
418The stack area may be statically allocated using
419:c:macro:`K_THREAD_STACK_DEFINE` or :c:macro:`K_KERNEL_STACK_DEFINE` to ensure
420it is properly set up in memory.
421
422The size parameter for the stack must be one of three values:
423
424- The original requested stack size passed to
425  ``K_THREAD_STACK`` or ``K_KERNEL_STACK`` family of stack instantiation
426  macros.
427- For a stack object defined with the ``K_THREAD_STACK`` family of
428  macros, the return value of :c:macro:`K_THREAD_STACK_SIZEOF()` for that'
429  object.
430- For a stack object defined with the ``K_KERNEL_STACK`` family of
431  macros, the return value of :c:macro:`K_KERNEL_STACK_SIZEOF()` for that
432  object.
433
434Alternatively, the stack area may be dynamically allocated using
435:c:func:`k_thread_stack_alloc` and freed using :c:func:`k_thread_stack_free`.
436
437The thread spawning function returns its thread id, which can be used
438to reference the thread.
439
440The following code spawns a thread that starts immediately.
441
442.. code-block:: c
443
444    #define MY_STACK_SIZE 500
445    #define MY_PRIORITY 5
446
447    extern void my_entry_point(void *, void *, void *);
448
449    K_THREAD_STACK_DEFINE(my_stack_area, MY_STACK_SIZE);
450    struct k_thread my_thread_data;
451
452    k_tid_t my_tid = k_thread_create(&my_thread_data, my_stack_area,
453                                     K_THREAD_STACK_SIZEOF(my_stack_area),
454                                     my_entry_point,
455                                     NULL, NULL, NULL,
456                                     MY_PRIORITY, 0, K_NO_WAIT);
457
458Alternatively, a thread can be declared at compile time by calling
459:c:macro:`K_THREAD_DEFINE`. Observe that the macro defines
460the stack area, control block, and thread id variables automatically.
461
462The following code has the same effect as the code segment above.
463
464.. code-block:: c
465
466    #define MY_STACK_SIZE 500
467    #define MY_PRIORITY 5
468
469    extern void my_entry_point(void *, void *, void *);
470
471    K_THREAD_DEFINE(my_tid, MY_STACK_SIZE,
472                    my_entry_point, NULL, NULL, NULL,
473                    MY_PRIORITY, 0, 0);
474
475.. note::
476   The delay parameter to :c:func:`k_thread_create` is a
477   :c:type:`k_timeout_t` value, so :c:macro:`K_NO_WAIT` means to start the
478   thread immediately. The corresponding parameter to :c:macro:`K_THREAD_DEFINE`
479   is a duration in integral milliseconds, so the equivalent argument is 0.
480
481The following code dynamically allocates a thread stack, waits until the thread
482has joined, and then frees the dynamically allocated thread stack.
483
484.. code-block:: c
485
486    extern void my_entry_point(void *, void *, void *);
487
488    k_tid_t my_tid;
489    void *my_stack_area;
490
491    my_stack_area = k_thread_stack_alloc(CONFIG_DYNAMIC_THREAD_STACK_SIZE);
492    my_tid = k_thread_create(&my_thread_data, my_stack_area,
493                              CONFIG_DYNAMIC_THREAD_STACK_SIZE,
494                              my_entry_point,
495                              NULL, NULL, NULL,
496                              MY_PRIORITY, 0, K_NO_WAIT);
497    k_thread_join(my_tid, K_FOREVER);
498    k_thread_stack_free(my_stack_area);
499
500User Mode Constraints
501---------------------
502
503This section only applies if :kconfig:option:`CONFIG_USERSPACE` is enabled, and a user
504thread tries to create a new thread. The :c:func:`k_thread_create` API is
505still used, but there are additional constraints which must be met or the
506calling thread will be terminated:
507
508* The calling thread must have permissions granted on both the child thread
509  and stack parameters; both are tracked by the kernel as kernel objects.
510
511* The child thread and stack objects must be in an uninitialized state,
512  i.e. it is not currently running and the stack memory is unused.
513
514* The stack size parameter passed in must be equal to or less than the
515  bounds of the stack object when it was declared.
516
517* The :c:macro:`K_USER` option must be used, as user threads can only create
518  other user threads.
519
520* The :c:macro:`K_ESSENTIAL` option must not be used, user threads may not be
521  considered essential threads.
522
523* The priority of the child thread must be a valid priority value, and equal to
524  or lower than the parent thread.
525
526Dropping Permissions
527====================
528
529If :kconfig:option:`CONFIG_USERSPACE` is enabled, a thread running in supervisor mode
530may perform a one-way transition to user mode using the
531:c:func:`k_thread_user_mode_enter` API. This is a one-way operation which
532will reset and zero the thread's stack memory. The thread will be marked
533as non-essential.
534
535Terminating a Thread
536====================
537
538A thread terminates itself by returning from its entry point function.
539
540The following code illustrates the ways a thread can terminate.
541
542.. code-block:: c
543
544    void my_entry_point(int unused1, int unused2, int unused3)
545    {
546        while (1) {
547            ...
548	    if (<some condition>) {
549	        return; /* thread terminates from mid-entry point function */
550	    }
551	    ...
552        }
553
554        /* thread terminates at end of entry point function */
555    }
556
557If :kconfig:option:`CONFIG_USERSPACE` is enabled, aborting a thread will additionally
558mark the thread and stack objects as uninitialized so that they may be re-used.
559
560Runtime Statistics
561******************
562
563Thread runtime statistics can be gathered and retrieved if
564:kconfig:option:`CONFIG_THREAD_RUNTIME_STATS` is enabled, for example, total number of
565execution cycles of a thread.
566
567By default, the runtime statistics are gathered using the default kernel
568timer. For some architectures, SoCs or boards, there are timers with higher
569resolution available via timing functions. Using of these timers can be
570enabled via :kconfig:option:`CONFIG_THREAD_RUNTIME_STATS_USE_TIMING_FUNCTIONS`.
571
572Here is an example:
573
574.. code-block:: c
575
576   k_thread_runtime_stats_t rt_stats_thread;
577
578   k_thread_runtime_stats_get(k_current_get(), &rt_stats_thread);
579
580   printk("Cycles: %llu\n", rt_stats_thread.execution_cycles);
581
582Suggested Uses
583**************
584
585Use threads to handle processing that cannot be handled in an ISR.
586
587Use separate threads to handle logically distinct processing operations
588that can execute in parallel.
589
590
591Configuration Options
592**********************
593
594Related configuration options:
595
596* :kconfig:option:`CONFIG_MAIN_THREAD_PRIORITY`
597* :kconfig:option:`CONFIG_MAIN_STACK_SIZE`
598* :kconfig:option:`CONFIG_IDLE_STACK_SIZE`
599* :kconfig:option:`CONFIG_THREAD_CUSTOM_DATA`
600* :kconfig:option:`CONFIG_NUM_COOP_PRIORITIES`
601* :kconfig:option:`CONFIG_NUM_PREEMPT_PRIORITIES`
602* :kconfig:option:`CONFIG_TIMESLICING`
603* :kconfig:option:`CONFIG_TIMESLICE_SIZE`
604* :kconfig:option:`CONFIG_TIMESLICE_PRIORITY`
605* :kconfig:option:`CONFIG_USERSPACE`
606
607
608
609API Reference
610**************
611
612.. doxygengroup:: thread_apis
613
614.. doxygengroup:: thread_stack_api
615