1 /*=======0=========1=========2=========3=========4=========5=========6=========7=========8=========9=========0=========1====*/
2 // ==== Thread Management ====
4 \addtogroup CMSIS_RTOS_ThreadMgmt Thread Management
5 \ingroup CMSIS_RTOS CMSIS_RTOSv2
6 \brief Define, create, and control thread functions.
8 The Thread Management function group allows defining, creating, and controlling thread functions in the system.
10 \note Thread management functions cannot be called from \ref CMSIS_RTOS_ISR_Calls "Interrupt Service Routines".
15 Threads can be in the following states:
17 - \b RUNNING: The thread that is currently running is in the \b RUNNING state. Only one thread at a time can be in this
19 - \b READY: Threads which are ready to run are in the \b READY state. Once the \b RUNNING thread has terminated, or is
20 \b BLOCKED, the next \b READY thread with the highest priority becomes the \b RUNNING thread.
21 - \b BLOCKED: Threads that are blocked either delayed, waiting for an event to occur or suspended are in the \b BLOCKED
23 - \b TERMINATED: When \ref osThreadTerminate is called, threads are \b TERMINATED with resources not yet released.
24 - \b INACTIVE: Threads that are not created or have been terminated with all resources released are in the \b INACTIVE state.
26 \image html "ThreadStatus.png" "Thread State and State Transitions"
29 A CMSIS-RTOS assumes that threads are scheduled as shown in the figure <b>Thread State and State Transitions</b>. The thread
30 states change as follows:
31 - A thread is created using the function \ref osThreadNew. This puts the thread into the \b READY or \b RUNNING state
32 (depending on the thread priority).
33 - CMSIS-RTOS is pre-emptive. The active thread with the highest priority becomes the \b RUNNING thread provided it does not
34 wait for any event. The initial priority of a thread is defined with the \ref osThreadAttr_t but may be changed during
35 execution using the function \ref osThreadSetPriority.
36 - The \b RUNNING thread transfers into the \b BLOCKED state when it is delayed, waiting for an event or suspended.
37 - Active threads can be terminated any time using the function \ref osThreadTerminate. Threads can terminate also by just
38 returning from the thread function. Threads that are terminated are in the \b INACTIVE state and typically do not consume
39 any dynamic memory resources.
42 Refer to \ref threadConfig for RTX5 configuration options.
46 The following examples show various scenarios to create threads:
48 <b>Example 1 - Create a simple thread</b>
50 Create a thread out of the function thread1 using all default values for thread attributes and memory from the
51 \ref GlobalMemoryPool.
54 __NO_RETURN void thread1 (void *argument) {
62 osThreadNew(thread1, NULL, NULL); // Create thread with default settings
68 <b>Example 2 - Create thread with stack non-default stack size</b>
70 Similar to the simple thread all attributes are default. The stack is dynamically allocated from the \ref GlobalMemoryPool
72 \ref osThreadAttr_t.stack_size is used to pass the stack size in Bytes to osThreadNew.
75 __NO_RETURN void thread1 (void *argument) {
80 const osThreadAttr_t thread1_attr = {
81 .stack_size = 1024 // Create the thread stack with a size of 1024 bytes
86 osThreadNew(thread1, NULL, &thread1_attr); // Create thread with custom sized stack memory
91 <b>Example 3 - Create thread with statically allocated stack</b>
93 Similar to the simple thread all attributes are default. The stack is statically allocated using the \c uint64_t array
94 \c thread1_stk_1. This allocates 64*8 Bytes (=512 Bytes) with an alignment of 8 Bytes (mandatory for Cortex-M stack memory).
96 \ref osThreadAttr_t.stack_mem holds a pointer to the stacks lowest address.
98 \ref osThreadAttr_t.stack_size is used to pass the stack size in Bytes to osThreadNew.
101 __NO_RETURN void thread1 (void *argument) {
106 static uint64_t thread1_stk_1[64];
108 const osThreadAttr_t thread1_attr = {
109 .stack_mem = &thread1_stk_1[0],
110 .stack_size = sizeof(thread1_stk_1)
115 osThreadNew(thread1, NULL, &thread1_attr); // Create thread with statically allocated stack memory
120 <b>Example 4 - Thread with statically allocated task control block</b>
122 Typically this method is chosen together with a statically allocated stack as shown in Example 2.
124 #include "cmsis_os2.h"
126 //include rtx_os.h for types of RTX objects
129 __NO_RETURN void thread1 (void *argument) {
134 static osRtxThread_t thread1_tcb;
136 const osThreadAttr_t thread1_attr = {
137 .cb_mem = &thread1_tcb,
138 .cb_size = sizeof(thread1_tcb),
143 osThreadNew(thread1, NULL, &thread1_attr); // Create thread with custom tcb memory
148 <b>Example 5 - Create thread with a different priority</b>
150 The default priority of RTX is \ref osPriorityNormal. Often you want to run a task with a higher or lower priority. Using the
151 \ref osThreadAttr_t control structure you can set any initial priority required.
154 __NO_RETURN void thread1 (void *argument) {
159 const osThreadAttr_t thread1_attr = {
160 .priority = osPriorityHigh //Set initial thread priority to high
165 osThreadNew(thread1, NULL, &thread1_attr);
170 <b>Example 6 - Joinable threads</b>
172 In this example a master thread creates four threads with the \ref osThreadJoinable attribute. These will do some work and
173 return using the \ref osThreadExit call after finished. \ref osThreadJoin is used to synchronize the thread termination.
177 __NO_RETURN void worker (void *argument) {
178 ; // work a lot on data[]
183 __NO_RETURN void thread1 (void *argument) {
184 osThreadAttr_t worker_attr;
185 osThreadId_t worker_ids[4];
188 memset(&worker_attr, 0, sizeof(worker_attr));
189 worker_attr.attr_bits = osThreadJoinable;
191 worker_ids[0] = osThreadNew(worker, &data[0][0], &worker_attr);
192 worker_ids[1] = osThreadNew(worker, &data[1][0], &worker_attr);
193 worker_ids[2] = osThreadNew(worker, &data[2][0], &worker_attr);
194 worker_ids[3] = osThreadNew(worker, &data[3][0], &worker_attr);
196 osThreadJoin(worker_ids[0]);
197 osThreadJoin(worker_ids[1]);
198 osThreadJoin(worker_ids[2]);
199 osThreadJoin(worker_ids[3]);
207 /*=======0=========1=========2=========3=========4=========5=========6=========7=========8=========9=========0=========1====*/
209 \enum osThreadState_t
211 State of a thread as retrieved by \ref osThreadGetState. In case \b osThreadGetState fails or if it is called from an ISR, it
212 will return \c osThreadError, otherwise it returns the thread state.
215 /*=======0=========1=========2=========3=========4=========5=========6=========7=========8=========9=========0=========1====*/
220 The \b osPriority_t value specifies the priority for a thread. The default thread priority should be \a osPriorityNormal.
221 If a Thread is active that has a higher priority than the currently executing thread, then a thread switch occurs immediately
222 to execute the new task.
224 To prevent from a priority inversion, a CMSIS-RTOS compliant OS may optionally implement a <b>priority inheritance</b>
225 method. A priority inversion occurs when a high priority thread is waiting for a resource or event that is controlled by a
226 thread with a lower priority.
228 \note Priority inheritance only applies to mutexes.
231 /*=======0=========1=========2=========3=========4=========5=========6=========7=========8=========9=========0=========1====*/
233 \typedef void (*osThreadFunc_t) (void *argument)
237 /*=======0=========1=========2=========3=========4=========5=========6=========7=========8=========9=========0=========1====*/
239 \typedef osThreadId_t
242 /*=======0=========1=========2=========3=========4=========5=========6=========7=========8=========9=========0=========1====*/
244 \struct osThreadAttr_t
247 /*=======0=========1=========2=========3=========4=========5=========6=========7=========8=========9=========0=========1====*/
249 \def osThreadJoinable
252 See \ref osThreadJoin.
256 \def osThreadDetached
259 A thread in this state cannot be joined using \ref osThreadJoin.
262 /*=======0=========1=========2=========3=========4=========5=========6=========7=========8=========9=========0=========1====*/
264 \fn osThreadId_t osThreadNew (osThreadFunc_t func, void *argument, const osThreadAttr_t *attr)
266 The function \b osThreadNew starts a thread function by adding it to the list of active threads and sets it to state
267 \b READY. Arguments for the thread function are passed using the parameter pointer \a *argument. When the priority of the
268 created thread function is higher than the current \b RUNNING thread, the created thread function starts instantly and
269 becomes the new \b RUNNING thread. Thread attributes are defined with the parameter pointer \a attr. Attributes include
270 settings for thread priority, stack size, or memory allocation.
272 The function can be safely called before the RTOS is
273 started (call to \ref osKernelStart), but not before it is initialized (call to \ref osKernelInitialize).
275 The function \b osThreadNew returns the pointer to the thread object identifier or \token{NULL} in case of an error.
277 \note Cannot be called from \ref CMSIS_RTOS_ISR_Calls "Interrupt Service Routines".
280 /*=======0=========1=========2=========3=========4=========5=========6=========7=========8=========9=========0=========1====*/
282 \fn const char *osThreadGetName (osThreadId_t thread_id)
284 The function \b osThreadGetName returns the pointer to the name string of the thread identified by parameter \a thread_id or
285 \token{NULL} in case of an error.
287 \note This function \b cannot be called from \ref CMSIS_RTOS_ISR_Calls "Interrupt Service Routines".
291 void ThreadGetName_example (void) {
292 char id; // id for the currently running thread
294 id = osThreadGetName ();
296 // Failed to get the thread name; not in a thread
302 /*=======0=========1=========2=========3=========4=========5=========6=========7=========8=========9=========0=========1====*/
304 \fn osThreadId_t osThreadGetId (void)
306 The function \b osThreadGetId returns the thread object ID of the currently running thread or NULL in case of an error.
308 \note This function \b cannot be called from \ref CMSIS_RTOS_ISR_Calls "Interrupt Service Routines".
312 void ThreadGetId_example (void) {
313 osThreadId_t id; // id for the currently running thread
315 id = osThreadGetId ();
317 // Failed to get the id; not in a thread
322 /*=======0=========1=========2=========3=========4=========5=========6=========7=========8=========9=========0=========1====*/
324 \fn osThreadState_t osThreadGetState (osThreadId_t thread_id)
326 The function \b osThreadGetState returns the state of the thread identified by parameter \a thread_id. In case it fails or
327 if it is called from an ISR, it will return \c osThreadError, otherwise it returns the thread state (refer to
328 \ref osThreadState_t for the list of thread states).
330 \note This function \b cannot be called from \ref CMSIS_RTOS_ISR_Calls "Interrupt Service Routines".
333 /*=======0=========1=========2=========3=========4=========5=========6=========7=========8=========9=========0=========1====*/
335 \fn osStatus_t osThreadSetPriority (osThreadId_t thread_id, osPriority_t priority)
337 The function \b osThreadSetPriority changes the priority of an active thread specified by the parameter \a thread_id to the
338 priority specified by the parameter \a priority.
340 Possible \ref osStatus_t return values:
341 - \em osOK: the priority of the specified thread has been changed successfully.
342 - \em osErrorParameter: \a thread_id is \token{NULL} or invalid or \a priority is incorrect.
343 - \em osErrorResource: thread specified by parameter \em thread_id is in an invalid thread state.
344 - \em osErrorISR: the function \b osThreadSetPriority cannot be called from interrupt service routines.
346 \note This function \b cannot be called from \ref CMSIS_RTOS_ISR_Calls "Interrupt Service Routines".
350 #include "cmsis_os2.h"
352 void Thread_1 (void const *arg) { // Thread function
353 osThreadId_t id; // id for the currently running thread
354 osStatus_t status; // status of the executed function
357 id = osThreadGetId (); // Obtain ID of current running thread
359 status = osThreadSetPriority (id, osPriorityBelowNormal); // Set thread priority
360 if (status == osOK) {
361 // Thread priority changed to BelowNormal
364 // Failed to set the priority
370 /*=======0=========1=========2=========3=========4=========5=========6=========7=========8=========9=========0=========1====*/
372 \fn osPriority_t osThreadGetPriority (osThreadId_t thread_id)
374 The function \b osThreadGetPriority returns the priority of an active thread specified by the parameter \a thread_id.
376 Possible \ref osPriority_t return values:
377 - \em priority: the priority of the specified thread.
378 - \em osPriorityError: priority cannot be determined or is illegal. It is also returned when the function is called from
379 \ref CMSIS_RTOS_ISR_Calls "Interrupt Service Routines".
381 \note This function \b cannot be called from \ref CMSIS_RTOS_ISR_Calls "Interrupt Service Routines".
385 #include "cmsis_os2.h"
387 void Thread_1 (void const *arg) { // Thread function
388 osThreadId_t id; // id for the currently running thread
389 osPriority_t priority; // thread priority
391 id = osThreadGetId (); // Obtain ID of current running thread
392 priority = osThreadGetPriority (id); // Obtain the thread priority
396 /*=======0=========1=========2=========3=========4=========5=========6=========7=========8=========9=========0=========1====*/
398 \fn osStatus_t osThreadYield (void)
400 The function \b osThreadYield passes control to the next thread that is in the \b READY state. If there is no other thread in
401 state \b READY, then the current thread continues execution and no thread switching occurs.
403 Possible \ref osStatus_t return values:
404 - \em osOK: control has been passed to the next thread successfully.
405 - \em osError: an unspecified error has occurred.
406 - \em osErrorISR: the function \b osThreadYield cannot be called from interrupt service routines.
408 \note This function \b cannot be called from \ref CMSIS_RTOS_ISR_Calls "Interrupt Service Routines".
412 #include "cmsis_os2.h"
414 void Thread_1 (void const *arg) { // Thread function
415 osStatus_t status; // status of the executed function
418 status = osThreadYield(); //
419 if (status != osOK) {
426 /*=======0=========1=========2=========3=========4=========5=========6=========7=========8=========9=========0=========1====*/
428 \fn osStatus_t osThreadSuspend (osThreadId_t thread_id)
430 The function \b osThreadSuspend suspends the execution of the thread identified by parameter \em thread_id. The thread is put
431 into the \em BLOCKED state (\ref osThreadBlocked). The thread is not executed until restarted with the function
434 Threads that are already \em BLOCKED are removed from any wait list and become ready when they are resumed.
435 Thus it is not recommended to suspend an already blocked thread.
437 Possible \ref osStatus_t return values:
438 - \em osOK: the thread has been suspended successfully.
439 - \em osErrorParameter: \a thread_id is \token{NULL} or invalid.
440 - \em osErrorResource: thread specified by parameter \em thread_id is in an invalid thread state.
441 - \em osErrorISR: the function \b osThreadSuspend cannot be called from interrupt service routines.
443 \note This function \b cannot be called from \ref CMSIS_RTOS_ISR_Calls "Interrupt Service Routines".
446 /*=======0=========1=========2=========3=========4=========5=========6=========7=========8=========9=========0=========1====*/
448 \fn osStatus_t osThreadResume (osThreadId_t thread_id)
450 The function \b osThreadResume forces a thread identified by parameter \em thread_id which is is \em BLOCKED state to resume operation.
452 The thread becomes ready regardless of the reason why the thread was blocked. Thus it is not recommended to resume a thread not suspended
453 by \ref osThreadSuspend.
455 Functions that will put a thread into \em BLOCKED state are:
456 \ref osEventFlagsWait and \ref osThreadFlagsWait,
457 \ref osDelay and \ref osDelayUntil,
458 \ref osMutexAcquire and \ref osSemaphoreAcquire,
459 \ref osMessageQueueGet,
460 \ref osMemoryPoolAlloc,
462 \ref osThreadSuspend.
464 Possible \ref osStatus_t return values:
465 - \em osOK: the thread has been resumed successfully.
466 - \em osErrorParameter: \a thread_id is \token{NULL} or invalid.
467 - \em osErrorResource: thread specified by parameter \em thread_id is in an invalid thread state.
468 - \em osErrorISR: the function \b osThreadResume cannot be called from interrupt service routines.
470 \note This function \b cannot be called from \ref CMSIS_RTOS_ISR_Calls "Interrupt Service Routines".
473 /*=======0=========1=========2=========3=========4=========5=========6=========7=========8=========9=========0=========1====*/
475 \fn osStatus_t osThreadDetach (osThreadId_t thread_id)
477 The function \b osThreadDetach changes the attribute of a thread (specified by \em thread_id) to \ref osThreadDetached.
478 Detached threads are not joinable with \ref osThreadJoin. When a detached thread is terminated, all resources are returned to
479 the system. The behavior of \ref osThreadDetach on an already detached thread is undefined.
481 Possible \ref osStatus_t return values:
482 - \em osOK: the attribute of the specified thread has been changed to detached successfully.
483 - \em osErrorParameter: \a thread_id is \token{NULL} or invalid.
484 - \em osErrorResource: thread specified by parameter \em thread_id is in an invalid thread state.
485 - \em osErrorISR: the function \b osThreadDetach cannot be called from interrupt service routines.
487 \note This function \b cannot be called from \ref CMSIS_RTOS_ISR_Calls "Interrupt Service Routines".
490 /*=======0=========1=========2=========3=========4=========5=========6=========7=========8=========9=========0=========1====*/
492 \fn osStatus_t osThreadJoin (osThreadId_t thread_id)
494 The function \b osThreadJoin waits for the thread specified by \em thread_id to terminate. If that thread has already
495 terminated, then \ref osThreadJoin returns immediately. The thread must be joinable. By default threads are created with the
496 attribute \ref osThreadJoinable.
498 Possible \ref osStatus_t return values:
499 - \em osOK: if the thread has already been terminated and joined or once the thread has been terminated and the join
501 - \em osErrorParameter: \a thread_id is \token{NULL} or invalid.
502 - \em osErrorResource: parameter \em thread_id is \token{NULL} or refers to a thread that is not an active thread or the
503 thread is not joinable.
504 - \em osErrorISR: the function \b osThreadJoin cannot be called from interrupt service routines.
506 \note This function \b cannot be called from \ref CMSIS_RTOS_ISR_Calls "Interrupt Service Routines".
509 /*=======0=========1=========2=========3=========4=========5=========6=========7=========8=========9=========0=========1====*/
511 \fn __NO_RETURN void osThreadExit (void)
514 The function \b osThreadExit terminates the calling thread. This allows the thread to be synchronized with \ref osThreadJoin.
516 \note This function \b cannot be called from \ref CMSIS_RTOS_ISR_Calls "Interrupt Service Routines".
520 __NO_RETURN void worker (void *argument) {
528 /*=======0=========1=========2=========3=========4=========5=========6=========7=========8=========9=========0=========1====*/
530 \fn osStatus_t osThreadTerminate (osThreadId_t thread_id)
532 The function \b osThreadTerminate removes the thread specified by parameter \a thread_id from the list of active threads. If
533 the thread is currently \b RUNNING, the thread terminates and the execution continues with the next \b READY thread. If no
534 such thread exists, the function will not terminate the running thread, but return \em osErrorResource.
536 Possible \ref osStatus_t return values:
537 - \em osOK: the specified thread has been removed from the active thread list successfully.
538 - \em osErrorParameter: \a thread_id is \token{NULL} or invalid.
539 - \em osErrorResource: thread specified by parameter \em thread_id is in an invalid thread state or no
540 other \b READY thread exists.
541 - \em osErrorISR: the function \b osThreadTerminate cannot be called from interrupt service routines.
543 \note This function \b cannot be called from \ref CMSIS_RTOS_ISR_Calls "Interrupt Service Routines".
544 \note Avoid calling the function with a \em thread_id that does not exist or has been terminated already.
548 #include "cmsis_os2.h"
550 void Thread_1 (void *arg); // function prototype for Thread_1
552 void ThreadTerminate_example (void) {
556 id = osThreadNew (Thread_1, NULL, NULL); // create the thread
558 status = osThreadTerminate (id); // stop the thread
559 if (status == osOK) {
560 // Thread was terminated successfully
563 // Failed to terminate a thread
569 /*=======0=========1=========2=========3=========4=========5=========6=========7=========8=========9=========0=========1====*/
571 \fn uint32_t osThreadGetStackSize (osThreadId_t thread_id)
573 The function \b osThreadGetStackSize returns the stack size of the thread specified by parameter \a thread_id. In case of an
574 error, it returns \token{0}.
576 \note This function \b cannot be called from \ref CMSIS_RTOS_ISR_Calls "Interrupt Service Routines".
579 /*=======0=========1=========2=========3=========4=========5=========6=========7=========8=========9=========0=========1====*/
581 \fn uint32_t osThreadGetStackSpace (osThreadId_t thread_id);
583 The function \b osThreadGetStackSpace returns the size of unused stack space for the thread specified by parameter
584 \a thread_id. Stack watermark recording during execution needs to be enabled (refer to \ref threadConfig). In case of an
585 error, it returns \token{0}.
587 \note This function \b cannot be called from \ref CMSIS_RTOS_ISR_Calls "Interrupt Service Routines".
590 /*=======0=========1=========2=========3=========4=========5=========6=========7=========8=========9=========0=========1====*/
592 \fn uint32_t osThreadGetCount (void)
594 The function \b osThreadGetCount returns the number of active threads or \token{0} in case of an error.
596 \note This function \b cannot be called from \ref CMSIS_RTOS_ISR_Calls "Interrupt Service Routines".
599 /*=======0=========1=========2=========3=========4=========5=========6=========7=========8=========9=========0=========1====*/
601 \fn uint32_t osThreadEnumerate (osThreadId_t *thread_array, uint32_t array_items)
603 The function \b osThreadEnumerate returns the number of enumerated threads or \token{0} in case of an error.
605 \note This function \b cannot be called from \ref CMSIS_RTOS_ISR_Calls "Interrupt Service Routines".
611 // these struct members must stay outside the group to avoid double entries in documentation
613 \var osThreadAttr_t::attr_bits
615 The following predefined bit masks can be assigned to set options for a thread object.
617 Bit Mask | Description
618 :-----------------------|:-----------------------------------------
619 osThreadJoinable | Thread is created in a join-able state.
620 osThreadDetached | Thread is created in a detached state (default).
622 \var osThreadAttr_t::cb_mem
624 Pointer to a memory location for the thread object. This can optionally be used for custom memory management systems.
625 Specify \token{NULL} to use the kernel memory management.
627 \var osThreadAttr_t::cb_size
629 The size of the memory block passed with \ref cb_mem. Must be the size of a thread control block object or larger.
631 \var osThreadAttr_t::name
633 String with a human readable name of the thread object.
635 \var osThreadAttr_t::priority
637 Specifies the initial thread priority with a value from #osPriority_t.
639 \var osThreadAttr_t::reserved
641 Reserved for future use. Must be \token{0}.
643 \var osThreadAttr_t::stack_mem
645 Pointer to a memory location for the thread stack, \b must be 64-bit aligned. This can optionally be used for custom memory management systems.
646 Specify \token{NULL} to use the kernel memory management.
648 \var osThreadAttr_t::tz_module
650 TrustZone Thread Context Management Identifier to allocate context memory for threads. The RTOS kernel that runs in
651 non-secure state calls the interface functions defined by the header file TZ_context.h.
652 See <a href="../../Core/html/group__context__trustzone__functions.html">TrustZone RTOS Context Management</a>.
654 \var osThreadAttr_t::stack_size
656 The size of the stack in Bytes.