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 \ref ThreadStates "RUNNING" state. Only one thread at a time can be in this
19 - \b READY: Threads which are ready to run are in the \ref ThreadStates "READY" state. Once the \ref ThreadStates "RUNNING" thread has terminated, or is
20 \ref ThreadStates "BLOCKED", the next \ref ThreadStates "READY" thread with the highest priority becomes the \ref ThreadStates "RUNNING" thread.
21 - \b BLOCKED: Threads that are blocked either delayed, waiting for an event to occur or suspended are in the \ref ThreadStates "BLOCKED"
23 - \b TERMINATED: When \ref osThreadTerminate is called, threads are \ref ThreadStates "TERMINATED" with resources not yet released (applies to \ref joinable_threads "joinable threads).
24 - \b INACTIVE: Threads that are not created or have been terminated with all resources released are in the \ref ThreadStates "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 \ref ThreadStates "READY" or \ref ThreadStates "RUNNING" state
32 (depending on the thread priority).
33 - CMSIS-RTOS is preemptive. The active thread with the highest priority becomes the \ref ThreadStates "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 \ref ThreadStates "RUNNING" thread transfers into the \ref ThreadStates "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 \ref ThreadStates "INACTIVE" state and typically do not consume
39 any dynamic memory resources.
41 \anchor threadConfig_procmode
42 Processor Mode for Thread Execution
45 When creating user threads with \ref osThreadNew it is possible to specify for each thread whether it shall be executed in privileged or unprivileged mode. For that the thread attributes argument shall have in its osThreadAttr_t::attr_bits flags either \ref osThreadPrivileged or \ref osThreadUnprivileged set respectively.
46 If not set then the default operation mode will be used according to kernel configuration.
48 For detailed differences between privileged and unprivileged mode, please refer to the User's Guide of the target processor. But typically following differences are specified:
50 In **unprivileged processor mode**, the thread :
51 - has limited access to the MSR and MRS instructions, and cannot use the CPS instruction.
52 - cannot access the system timer, NVIC, or system control block.
53 - might have restricted access to memory or peripherals.
55 In **privileged processor mode**, the application software can use all the instructions and has access to all resources.
57 \anchor thread_examples
60 The following examples show various scenarios to create threads:
62 <b>Example 1 - Create a simple thread</b>
64 Create a thread out of the function thread1 using all default values for thread attributes and memory allocated by the system.
67 __NO_RETURN void thread1 (void *argument) {
75 osThreadNew(thread1, NULL, NULL); // Create thread with default settings
81 <b>Example 2 - Create thread with stack non-default stack size</b>
83 Similar to the simple thread all attributes are default. The stack size is requested of size 1024 Bytes with with corresponding value passed as \ref osThreadAttr_t.stack_size to \ref osThreadNew. The memory for the stack is then allocated by the system.
86 __NO_RETURN void thread1 (void *argument) {
91 const osThreadAttr_t thread1_attr = {
92 .stack_size = 1024 // Create the thread stack with a size of 1024 bytes
97 osThreadNew(thread1, NULL, &thread1_attr); // Create thread with custom sized stack memory
102 <b>Example 3 - Create thread with statically allocated stack</b>
104 Similar to the simple thread all attributes are default. The stack is statically allocated using the \c uint64_t array
105 \c thread1_stk_1. This allocates 64*8 Bytes (=512 Bytes) with an alignment of 8 Bytes (mandatory for Cortex-M stack memory).
107 \ref osThreadAttr_t.stack_mem holds a pointer to the stacks lowest address.
109 \ref osThreadAttr_t.stack_size is used to pass the stack size in Bytes to \ref osThreadNew.
112 __NO_RETURN void thread1 (void *argument) {
117 static uint64_t thread1_stk_1[64];
119 const osThreadAttr_t thread1_attr = {
120 .stack_mem = &thread1_stk_1[0],
121 .stack_size = sizeof(thread1_stk_1)
126 osThreadNew(thread1, NULL, &thread1_attr); // Create thread with statically allocated stack memory
131 <b>Example 4 - Thread with statically allocated task control block</b>
133 Typically this method is chosen together with a statically allocated stack as shown in Example 2.
135 #include "cmsis_os2.h"
137 //include rtx_os.h for control blocks of CMSIS-RTX objects
140 __NO_RETURN void thread1 (void *argument) {
145 static osRtxThread_t thread1_tcb;
147 const osThreadAttr_t thread1_attr = {
148 .cb_mem = &thread1_tcb,
149 .cb_size = sizeof(thread1_tcb),
154 osThreadNew(thread1, NULL, &thread1_attr); // Create thread with custom tcb memory
159 <b>Example 5 - Create thread with a different priority</b>
161 The default priority of RTX kernel is \token{osPriorityNormal}. Often you want to run a task with a higher or lower priority. Using the \ref osThreadAttr_t::priority field you can assign any initial priority required.
164 __NO_RETURN void thread1 (void *argument) {
169 const osThreadAttr_t thread1_attr = {
170 .priority = osPriorityHigh //Set initial thread priority to high
175 osThreadNew(thread1, NULL, &thread1_attr);
180 \anchor joinable_threads
181 <b>Example 6 - Joinable threads</b>
183 In this example a master thread creates four threads with the \ref osThreadJoinable attribute. These will do some work and
184 return using the \ref osThreadExit call after finished. \ref osThreadJoin is used to synchronize the thread termination.
188 __NO_RETURN void worker (void *argument) {
189 ; // work a lot on data[]
194 __NO_RETURN void thread1 (void *argument) {
195 osThreadAttr_t worker_attr;
196 osThreadId_t worker_ids[4];
199 memset(&worker_attr, 0, sizeof(worker_attr));
200 worker_attr.attr_bits = osThreadJoinable;
202 worker_ids[0] = osThreadNew(worker, &data[0][0], &worker_attr);
203 worker_ids[1] = osThreadNew(worker, &data[1][0], &worker_attr);
204 worker_ids[2] = osThreadNew(worker, &data[2][0], &worker_attr);
205 worker_ids[3] = osThreadNew(worker, &data[3][0], &worker_attr);
207 osThreadJoin(worker_ids[0]);
208 osThreadJoin(worker_ids[1]);
209 osThreadJoin(worker_ids[2]);
210 osThreadJoin(worker_ids[3]);
218 /*=======0=========1=========2=========3=========4=========5=========6=========7=========8=========9=========0=========1====*/
220 \typedef osThreadState_t
222 State of a thread as retrieved by \ref osThreadGetState. In case \b osThreadGetState fails or if it is called from an ISR, it
223 will return \c osThreadError, otherwise it returns the thread state.
225 \var osThreadState_t::osThreadInactive
226 \details The thread is created but not actively used, or has been terminated (returned for static control block allocation, when memory pools are used \ref osThreadError is returned as the control block is no longer valid)
228 \var osThreadState_t::osThreadReady
229 \details The thread is ready for execution but not currently running.
231 \var osThreadState_t::osThreadRunning
232 \details The thread is currently running.
234 \var osThreadState_t::osThreadBlocked
235 \details The thread is currently blocked (delayed, waiting for an event or suspended).
237 \var osThreadState_t::osThreadTerminated
238 \details The thread is terminated and all its resources are not yet freed (applies to \ref joinable_threads "joinable threads).
240 \var osThreadState_t::osThreadError
241 \details The thread does not exist (has raised an error condition) and cannot be scheduled.
244 /*=======0=========1=========2=========3=========4=========5=========6=========7=========8=========9=========0=========1====*/
246 \typedef osPriority_t
249 The \b osPriority_t value specifies the priority for a thread. The default thread priority should be \a osPriorityNormal.
250 If an active thread becomes ready that has a higher priority than the currently running thread then a thread switch occurs
251 immediately. The system continues executing the thread with the higher priority.
253 To prevent from a priority inversion, a CMSIS-RTOS compliant OS may optionally implement a <b>priority inheritance</b>
254 method. A priority inversion occurs when a high priority thread is waiting for a resource or event that is controlled by a
255 thread with a lower priority. Thus causing the high priority thread potentially being blocked forever by another thread
256 with lower priority. To come over this issue the low priority thread controlling the resource should be treated as having
257 the higher priority until it releases the resource.
259 \note Priority inheritance only applies to mutexes.
261 \var osPriority_t::osPriorityIdle
262 \details This lowest priority should not be used for any other thread.
264 \var osPriority_t::osPriorityISR
265 \details This highest priority might be used by the RTOS implementation but must not be used for any user thread.
268 /*=======0=========1=========2=========3=========4=========5=========6=========7=========8=========9=========0=========1====*/
270 \typedef void (*osThreadFunc_t) (void *argument)
271 \details Entry function for threads. Setting up a new thread (\ref osThreadNew) will start execution with a call into this
272 entry function. The optional argument can be used to hand over arbitrary user data to the thread, i.e. to identify the thread
273 or for runtime parameters.
275 \param[in] argument Arbitrary user data set on \ref osThreadNew.
278 /*=======0=========1=========2=========3=========4=========5=========6=========7=========8=========9=========0=========1====*/
280 \typedef osThreadId_t
281 \details Returned by:
284 - \ref osThreadEnumerate
285 - \ref osMutexGetOwner
288 /*=======0=========1=========2=========3=========4=========5=========6=========7=========8=========9=========0=========1====*/
290 \struct osThreadAttr_t
291 \details Specifies the following attributes for the \ref osThreadNew function.
293 /*=======0=========1=========2=========3=========4=========5=========6=========7=========8=========9=========0=========1====*/
297 \details Error return code from \ref osThreadGetClass and \ref osThreadGetZone.
299 /*=======0=========1=========2=========3=========4=========5=========6=========7=========8=========9=========0=========1====*/
302 \def osThreadJoinable
304 Bitmask for a thread that can be joined.
305 Intended for use in \e attr_bits of \ref osThreadAttr_t type argument for \ref osThreadNew function.
307 A thread in this state can be joined using \ref osThreadJoin.
309 /*=======0=========1=========2=========3=========4=========5=========6=========7=========8=========9=========0=========1====*/
312 \def osThreadDetached
314 Bitmask for a thread that cannot be joined.
315 Intended for use in \e attr_bits of \ref osThreadAttr_t type argument for \ref osThreadNew function.
317 A thread in this state cannot be joined using \ref osThreadJoin.
320 /*=======0=========1=========2=========3=========4=========5=========6=========7=========8=========9=========0=========1====*/
322 \def osThreadUnprivileged
324 Bitmask for a thread that runs in unprivileged mode.
325 Intended for use in \e attr_bits of \ref osThreadAttr_t type argument for \ref osThreadNew function.
327 In \b unprivileged processor mode, a thread:
328 - has limited access to the MSR and MRS instructions, and cannot use the CPS instruction.
329 - cannot access the system timer, NVIC, or system control block.
330 - might have restricted access to memory or peripherals.
332 \note Ignored on processors that only run in privileged mode.
334 Refer to the target processor User's Guide for details.
338 \def osThreadPrivileged
340 Bitmask for a thread that runs in privileged mode.
341 Intended for use in \e attr_bits of \ref osThreadAttr_t type argument for \ref osThreadNew function.
343 In \b privileged processor mode, the application software can use all the instructions and has access to all resources.
346 /*=======0=========1=========2=========3=========4=========5=========6=========7=========8=========9=========0=========1====*/
349 \param n MPU Protected Zone value.
350 \brief MPU zone value in attribute bit field format.
353 The preprocessor macro \b osThreadZone constructs attribute bitmask with MPU zone bits set to \a n.
357 /* ThreadB thread attributes */
358 const osThreadAttr_t thread_B_attr = {
359 .name = "ThreadB", // human readable thread name
360 .attr_bits = osThreadZone(3U) // assign thread to MPU zone 3
365 /*=======0=========1=========2=========3=========4=========5=========6=========7=========8=========9=========0=========1====*/
367 \def osThreadProcessor(n)
368 \param n Processor number.
369 \brief Thread processor affinity mask value in attribute affinity_mask format.
372 The preprocessor macro \b osThreadProcessor constructs attribute affinity_mask derived from \a n.
376 /*=======0=========1=========2=========3=========4=========5=========6=========7=========8=========9=========0=========1====*/
378 \fn osThreadId_t osThreadNew (osThreadFunc_t func, void *argument, const osThreadAttr_t *attr)
380 The function \b osThreadNew starts a thread function by adding it to the list of active threads and sets it to state
381 \ref ThreadStates "READY". Arguments for the thread function are passed using the parameter pointer \a *argument. When the priority of the
382 created thread function is higher than the current \ref ThreadStates "RUNNING" thread, the created thread function starts instantly and
383 becomes the new \ref ThreadStates "RUNNING" thread. Thread attributes are defined with the parameter pointer \a attr. Attributes include
384 settings for thread priority, stack size, or memory allocation.
386 The function can be safely called before the RTOS is
387 started (call to \ref osKernelStart), but not before it is initialized (call to \ref osKernelInitialize).
389 The function \b osThreadNew returns the pointer to the thread object identifier or \token{NULL} in case of an error.
391 \note Cannot be called from \ref CMSIS_RTOS_ISR_Calls "Interrupt Service Routines".
395 Refer to the \ref thread_examples "Thread Examples" section.
398 /*=======0=========1=========2=========3=========4=========5=========6=========7=========8=========9=========0=========1====*/
400 \fn const char *osThreadGetName (osThreadId_t thread_id)
402 The function \b osThreadGetName returns the pointer to the name string of the thread identified by parameter \a thread_id or
403 \token{NULL} in case of an error.
405 \note This function may be called from \ref CMSIS_RTOS_ISR_Calls "Interrupt Service Routines".
409 void ThreadGetName_example (void) {
410 osThreadId_t thread_id = osThreadGetId();
411 const char* name = osThreadGetName(thread_id);
413 // Failed to get the thread name; not in a thread
419 /*=======0=========1=========2=========3=========4=========5=========6=========7=========8=========9=========0=========1====*/
421 \fn uint32_t osThreadGetClass (osThreadId_t thread_id);
423 The function \b osThreadGetClass returns safety class assigned to the thread identified by parameter \a thread_id. In case of an
424 error, it returns \ref osErrorId.
427 /*=======0=========1=========2=========3=========4=========5=========6=========7=========8=========9=========0=========1====*/
429 \fn uint32_t osThreadGetZone (osThreadId_t thread_id);
431 The function \b osThreadGetZone returns the MPU Protected Zone value assigned to the thread identified by parameter \a thread_id.
432 In case of an error, it returns \ref osErrorId.
435 /*=======0=========1=========2=========3=========4=========5=========6=========7=========8=========9=========0=========1====*/
437 \fn osThreadId_t osThreadGetId (void)
439 The function \b osThreadGetId returns the thread object ID of the currently running thread or NULL in case of an error.
441 \note This function may be called from \ref CMSIS_RTOS_ISR_Calls "Interrupt Service Routines".
445 void ThreadGetId_example (void) {
446 osThreadId_t id; // id for the currently running thread
448 id = osThreadGetId();
450 // Failed to get the id
455 /*=======0=========1=========2=========3=========4=========5=========6=========7=========8=========9=========0=========1====*/
457 \fn osThreadState_t osThreadGetState (osThreadId_t thread_id)
459 The function \b osThreadGetState returns the state of the thread identified by parameter \a thread_id. In case it fails or
460 if it is called from an ISR, it will return \c osThreadError, otherwise it returns the thread state (refer to
461 \ref osThreadState_t for the list of thread states).
463 \note This function \b cannot be called from \ref CMSIS_RTOS_ISR_Calls "Interrupt Service Routines".
466 /*=======0=========1=========2=========3=========4=========5=========6=========7=========8=========9=========0=========1====*/
468 \fn osStatus_t osThreadSetPriority (osThreadId_t thread_id, osPriority_t priority)
470 The function \b osThreadSetPriority changes the priority of an active thread specified by the parameter \a thread_id to the
471 priority specified by the parameter \a priority.
473 Possible \ref osStatus_t return values:
474 - \em osOK: the priority of the specified thread has been changed successfully.
475 - \em osErrorParameter: \a thread_id is \token{NULL} or invalid or \a priority is incorrect.
476 - \em osErrorResource: the thread is in an invalid state.
477 - \em osErrorISR: the function \b osThreadSetPriority cannot be called from interrupt service routines.
478 - \em osErrorSafetyClass: the calling thread safety class is lower than the safety class of the specified thread.
480 \note This function \b cannot be called from \ref CMSIS_RTOS_ISR_Calls "Interrupt Service Routines".
484 #include "cmsis_os2.h"
486 void Thread_1 (void const *arg) { // Thread function
487 osThreadId_t id; // id for the currently running thread
488 osStatus_t status; // status of the executed function
491 id = osThreadGetId(); // Obtain ID of current running thread
493 status = osThreadSetPriority(id, osPriorityBelowNormal); // Set thread priority
494 if (status == osOK) {
495 // Thread priority changed to BelowNormal
498 // Failed to set the priority
504 /*=======0=========1=========2=========3=========4=========5=========6=========7=========8=========9=========0=========1====*/
506 \fn osPriority_t osThreadGetPriority (osThreadId_t thread_id)
508 The function \b osThreadGetPriority returns the priority of an active thread specified by the parameter \a thread_id.
510 Possible \ref osPriority_t return values:
511 - \em priority: the priority of the specified thread.
512 - \em osPriorityError: priority cannot be determined or is illegal. It is also returned when the function is called from
513 \ref CMSIS_RTOS_ISR_Calls "Interrupt Service Routines".
515 \note This function \b cannot be called from \ref CMSIS_RTOS_ISR_Calls "Interrupt Service Routines".
519 #include "cmsis_os2.h"
521 void Thread_1 (void const *arg) { // Thread function
522 osThreadId_t id; // id for the currently running thread
523 osPriority_t priority; // thread priority
525 id = osThreadGetId(); // Obtain ID of current running thread
526 priority = osThreadGetPriority(id); // Obtain the thread priority
530 /*=======0=========1=========2=========3=========4=========5=========6=========7=========8=========9=========0=========1====*/
532 \fn osStatus_t osThreadYield (void)
534 The function \b osThreadYield passes control to the next thread with the same priority that is in the \ref ThreadStates "READY" state.
535 If there is no other thread with the same priority in state \ref ThreadStates "READY", then the current thread continues execution and
536 no thread switch occurs. \b osThreadYield does not set the thread to state \ref ThreadStates "BLOCKED". Thus no thread with a lower
537 priority will be scheduled even if threads in state \ref ThreadStates "READY" are available.
539 Possible \ref osStatus_t return values:
540 - \em osOK: control has been passed to the next thread successfully.
541 - \em osError: an unspecified error has occurred.
542 - \em osErrorISR: the function \b osThreadYield cannot be called from interrupt service routines.
544 \note This function \b cannot be called from \ref CMSIS_RTOS_ISR_Calls "Interrupt Service Routines".
545 \note This function <b>has no impact</b> when called when the kernel is locked, see \ref osKernelLock.
549 #include "cmsis_os2.h"
551 void Thread_1 (void const *arg) { // Thread function
552 osStatus_t status; // status of the executed function
555 status = osThreadYield();
556 if (status != osOK) {
563 /*=======0=========1=========2=========3=========4=========5=========6=========7=========8=========9=========0=========1====*/
565 \fn osStatus_t osThreadSuspend (osThreadId_t thread_id)
567 The function \b osThreadSuspend suspends the execution of the thread identified by parameter \em thread_id. The thread is put
568 into the \ref ThreadStates "BLOCKED" state (\ref osThreadBlocked). Suspending the running thread will cause a context switch to another
569 thread in \ref ThreadStates "READY" state immediately. The suspended thread is not executed until explicitly resumed with the function \ref osThreadResume.
571 Threads that are already \ref ThreadStates "BLOCKED" are removed from any wait list and become ready when they are resumed.
572 Thus it is not recommended to suspend an already blocked thread.
574 Possible \ref osStatus_t return values:
575 - \em osOK: the thread has been suspended successfully.
576 - \em osErrorParameter: \a thread_id is \token{NULL} or invalid.
577 - \em osErrorResource: the thread is in an invalid state.
578 - \em osErrorISR: the function \b osThreadSuspend cannot be called from interrupt service routines.
579 - \em osErrorSafetyClass: the calling thread safety class is lower than the safety class of the specified thread.
581 \note This function \b cannot be called from \ref CMSIS_RTOS_ISR_Calls "Interrupt Service Routines".
582 \note This function <b>must not</b> be called to suspend the running thread when the kernel is locked, i.e. \ref osKernelLock.
586 /*=======0=========1=========2=========3=========4=========5=========6=========7=========8=========9=========0=========1====*/
588 \fn osStatus_t osThreadResume (osThreadId_t thread_id)
590 The function \b osThreadResume puts the thread identified by parameter \em thread_id (which has to be in \ref ThreadStates "BLOCKED" state)
591 back to the \ref ThreadStates "READY" state. If the resumed thread has a higher priority than the running thread a context switch occurs immediately.
593 The thread becomes ready regardless of the reason why the thread was blocked. Thus it is not recommended to resume a thread not suspended
594 by \ref osThreadSuspend.
596 Functions that will put a thread into \ref ThreadStates "BLOCKED" state are:
597 \ref osEventFlagsWait and \ref osThreadFlagsWait,
598 \ref osDelay and \ref osDelayUntil,
599 \ref osMutexAcquire and \ref osSemaphoreAcquire,
600 \ref osMessageQueueGet,
601 \ref osMemoryPoolAlloc,
603 \ref osThreadSuspend.
605 Possible \ref osStatus_t return values:
606 - \em osOK: the thread has been resumed successfully.
607 - \em osErrorParameter: \a thread_id is \token{NULL} or invalid.
608 - \em osErrorResource: the thread is in an invalid state.
609 - \em osErrorISR: the function \b osThreadResume cannot be called from interrupt service routines.
610 - \em osErrorSafetyClass: the calling thread safety class is lower than the safety class of the specified thread.
612 \note This function \b cannot be called from \ref CMSIS_RTOS_ISR_Calls "Interrupt Service Routines".
613 \note This function <b>may be</b> called when kernel is locked (\ref osKernelLock). Under this circumstances
614 a potential context switch is delayed until the kernel gets unlocked, i.e. \ref osKernelUnlock or \ref osKernelRestoreLock.
618 /*=======0=========1=========2=========3=========4=========5=========6=========7=========8=========9=========0=========1====*/
620 \fn osStatus_t osThreadDetach (osThreadId_t thread_id)
622 The function \b osThreadDetach changes the attribute of a thread (specified by \em thread_id) to \ref osThreadDetached.
623 Detached threads are not joinable with \ref osThreadJoin. When a detached thread is terminated, all resources are returned to
624 the system. The behavior of \ref osThreadDetach on an already detached thread is undefined.
626 Possible \ref osStatus_t return values:
627 - \em osOK: the attribute of the specified thread has been changed to detached successfully.
628 - \em osErrorParameter: \a thread_id is \token{NULL} or invalid.
629 - \em osErrorResource: the thread is in an invalid state.
630 - \em osErrorISR: the function \b osThreadDetach cannot be called from interrupt service routines.
631 - \em osErrorSafetyClass: the calling thread safety class is lower than the safety class of the specified thread.
633 \note This function \b cannot be called from \ref CMSIS_RTOS_ISR_Calls "Interrupt Service Routines".
636 /*=======0=========1=========2=========3=========4=========5=========6=========7=========8=========9=========0=========1====*/
638 \fn osStatus_t osThreadJoin (osThreadId_t thread_id)
640 The function \b osThreadJoin waits for the thread specified by \em thread_id to terminate. If that thread has already
641 terminated, then \ref osThreadJoin returns immediately. The thread must be joinable. By default threads are created with the
642 attribute \ref osThreadDetached.
644 Possible \ref osStatus_t return values:
645 - \em osOK: if the thread has already been terminated and joined or once the thread has been terminated and the join
647 - \em osErrorParameter: \a thread_id is \token{NULL} or invalid.
648 - \em osErrorResource: the thread is in an invalid state (ex: not joinable).
649 - \em osErrorISR: the function \b osThreadJoin cannot be called from interrupt service routines.
650 - \em osErrorSafetyClass: the calling thread safety class is lower than the safety class of the specified thread.
652 \note This function \b cannot be called from \ref CMSIS_RTOS_ISR_Calls "Interrupt Service Routines". <br>
653 \note Only one thread shall call \b osThreadJoin to join the target thread. If multiple threads try to join simultaneously with the same thread,
654 the results are undefined.
658 /*=======0=========1=========2=========3=========4=========5=========6=========7=========8=========9=========0=========1====*/
660 \fn __NO_RETURN void osThreadExit (void)
663 The function \b osThreadExit terminates the calling thread. This allows the thread to be synchronized with \ref osThreadJoin.
665 \note This function \b cannot be called from \ref CMSIS_RTOS_ISR_Calls "Interrupt Service Routines".
669 __NO_RETURN void worker (void *argument) {
677 /*=======0=========1=========2=========3=========4=========5=========6=========7=========8=========9=========0=========1====*/
679 \fn osStatus_t osThreadTerminate (osThreadId_t thread_id)
681 The function \b osThreadTerminate removes the thread specified by parameter \a thread_id from the list of active threads. If
682 the thread is currently \ref ThreadStates "RUNNING", the thread terminates and the execution continues with the next \ref ThreadStates "READY" thread. If no
683 such thread exists, the function will not terminate the running thread, but return \em osErrorResource.
685 Possible \ref osStatus_t return values:
686 - \em osOK: the specified thread has been removed from the active thread list successfully.
687 - \em osErrorParameter: \a thread_id is \token{NULL} or invalid.
688 - \em osErrorResource: the thread is in an invalid state or no other \ref ThreadStates "READY" thread exists.
689 - \em osErrorISR: the function \b osThreadTerminate cannot be called from interrupt service routines.
690 - \em osErrorSafetyClass: the calling thread safety class is lower than the safety class of the specified thread.
692 \note This function \b cannot be called from \ref CMSIS_RTOS_ISR_Calls "Interrupt Service Routines".
693 \note Avoid calling the function with a \em thread_id that does not exist or has been terminated already.
694 \note \b osThreadTerminate destroys non-joinable threads and removes their thread_id from the system. Subsequent access to the
695 thread_id (for example \ref osThreadGetState) will return an \ref osThreadError. Joinable threads will not be destroyed and
696 return the status \ref osThreadTerminated until they are joined with \ref osThreadJoin.
700 #include "cmsis_os2.h"
702 void Thread_1 (void *arg); // function prototype for Thread_1
704 void ThreadTerminate_example (void) {
708 id = osThreadNew(Thread_1, NULL, NULL); // create the thread
710 status = osThreadTerminate(id); // stop the thread
711 if (status == osOK) {
712 // Thread was terminated successfully
715 // Failed to terminate a thread
721 /*=======0=========1=========2=========3=========4=========5=========6=========7=========8=========9=========0=========1====*/
723 \fn uint32_t osThreadGetStackSize (osThreadId_t thread_id)
725 The function \b osThreadGetStackSize returns the stack size of the thread specified by parameter \a thread_id. In case of an
726 error, it returns \token{0}.
728 \note This function \b cannot be called from \ref CMSIS_RTOS_ISR_Calls "Interrupt Service Routines".
731 /*=======0=========1=========2=========3=========4=========5=========6=========7=========8=========9=========0=========1====*/
733 \fn uint32_t osThreadGetStackSpace (osThreadId_t thread_id);
735 The function \b osThreadGetStackSpace returns the size of unused stack space for the thread specified by parameter \a thread_id. In case of an error, it returns \token{0}.
737 \note This function \b cannot be called from \ref CMSIS_RTOS_ISR_Calls "Interrupt Service Routines".
740 /*=======0=========1=========2=========3=========4=========5=========6=========7=========8=========9=========0=========1====*/
742 \fn uint32_t osThreadGetCount (void)
744 The function \b osThreadGetCount returns the number of active threads or \token{0} in case of an error.
746 \note This function \b cannot be called from \ref CMSIS_RTOS_ISR_Calls "Interrupt Service Routines".
749 /*=======0=========1=========2=========3=========4=========5=========6=========7=========8=========9=========0=========1====*/
751 \fn uint32_t osThreadEnumerate (osThreadId_t *thread_array, uint32_t array_items)
753 The function \b osThreadEnumerate returns the number of enumerated threads or \token{0} in case of an error.
755 \note This function \b cannot be called from \ref CMSIS_RTOS_ISR_Calls "Interrupt Service Routines".
758 /*=======0=========1=========2=========3=========4=========5=========6=========7=========8=========9=========0=========1====*/
760 \fn osStatus_t osThreadFeedWatchdog (uint32_t ticks);
762 The function \b osThreadFeedWatchdog restarts watchdog of the current running thread. If the thread watchdog is not fed again within the \a ticks interval \ref osWatchdogAlarm_Handler will be called.
764 Possible \ref osStatus_t return values:
765 - \em osOK: the watchdog timer was restarted successfully.
766 - \em osError: cannot be executed (kernel not running).
767 - \em osErrorISR: the function \b osThreadFeedWatchdog cannot be called from interrupt service routines.
769 \note This function \b cannot be called from \ref CMSIS_RTOS_ISR_Calls "Interrupt Service Routines".
773 #include "cmsis_os2.h"
775 void Thread_1 (void const *arg) { // Thread function
776 osStatus_t status; // Status of the executed function
779 status = osThreadFeedWatchdog(500U); // Feed thread watchdog for 500 ticks
780 // verify status value here
787 /*=======0=========1=========2=========3=========4=========5=========6=========7=========8=========9=========0=========1====*/
789 \fn osStatus_t osThreadProtectPrivileged (void);
791 The function \b osThreadProtectPrivileged disables creation of new privileged threads. After its successful execution, no new
792 threads with privilege execution mode (\ref osThreadPrivileged attribute) can be created.
793 Kernel shall be in ready state or running when \b osThreadProtectPrivileged is called.
795 Possible \ref osStatus_t return values:
796 - \em osOK: the creation of new privileged threads is disabled.
797 - \em osError: cannot be executed (kernel not ready).
798 - \em osErrorISR: the function \b osThreadProtectPrivileged cannot be called from interrupt service routines.
800 \note This function \b cannot be called from \ref CMSIS_RTOS_ISR_Calls "Interrupt Service Routines".
804 #include "cmsis_os2.h"
809 status = osKernelInitialize(); // Initialize CMSIS-RTOS2 kernel
810 // verify status value here.
811 : // Create privileged threads
812 status = osThreadProtectPrivileged(); // Disable creation of new privileged threads.
813 // verify status value here.
814 : // Start the kernel
819 /*=======0=========1=========2=========3=========4=========5=========6=========7=========8=========9=========0=========1====*/
821 \fn osStatus_t osThreadSuspendClass (uint32_t safety_class, uint32_t mode);
823 The function \b osThreadSuspendClass suspends execution of threads based on safety class assignment. \a safety_class provides the reference safety class value, while \a mode is considered as a bitmap that additionally specifies the safety classes to be suspended.
825 If \ref osSafetyWithSameClass is set in \a mode than the threads with safety class value equal to \a safety_class will be suspended.
827 If \ref osSafetyWithLowerClass is set in \a mode than the threads with safety class value lower than \a safety_class will be suspended.
829 Possible \ref osStatus_t return values:
830 - \em osOK: the threads with specified safety class have been suspended successfully.
831 - \em osErrorParameter: \a safety_class is invalid.
832 - \em osErrorResource: no other \ref ThreadStates "READY" thread exists.
833 - \em osErrorISR: the function \b osThreadSuspendClass is called from interrupt other than \ref osWatchdogAlarm_Handler.
834 - \em osErrorSafetyClass: the calling thread safety class is lower than the safety class specified by \a safety_class and \a mode.
838 #include "cmsis_os2.h"
840 void SuspendNonCriticalClasses (void) {
843 status = osThreadSuspendClass(4U, osSafetyWithSameClass | osSafetyWithLowerClass); // Suspends threads with safety class 4 or lower
844 // verify status value here.
849 /*=======0=========1=========2=========3=========4=========5=========6=========7=========8=========9=========0=========1====*/
851 \fn osStatus_t osThreadResumeClass (uint32_t safety_class, uint32_t mode);
853 The function \b osThreadResumeClass resumes execution of threads based on safety class assignment. \a safety_class provides the reference safety class value, while \a mode is considered as a bitmap that additionally specifies the safety classes to be resumed.
855 If \ref osSafetyWithSameClass is set in \a mode than the threads with safety class value equal to \a safety_class will be resumed.
857 If \ref osSafetyWithLowerClass is set in \a mode than the threads with safety class value lower than \a safety_class will be resumed.
860 Possible \ref osStatus_t return values:
861 - \em osOK: the threads with specified safety class have been resumed successfully.
862 - \em osErrorParameter: \a safety_class is invalid.
863 - \em osErrorISR: the function \b osThreadResumeClass is called from interrupt other than \ref osWatchdogAlarm_Handler.
864 - \em osErrorSafetyClass: the calling thread safety class is lower than the safety class specified by \a safety_class and \a mode.
868 #include "cmsis_os2.h"
870 void ResumeNonCriticalClasses (void) {
873 status = osThreadResumeClass(4U, osSafetyWithSameClass | osSafetyWithLowerClass); // Resumes threads with safety class 4 or lower
874 // verify status value here.
879 /*=======0=========1=========2=========3=========4=========5=========6=========7=========8=========9=========0=========1====*/
881 \fn osStatus_t osThreadTerminateZone (uint32_t zone);
883 The function \b osThreadTerminateZone terminates execution of threads assigned to the MPU Protected Zone as given by \a zone parameter.
885 Possible \ref osStatus_t return values:
886 - \em osOK: the threads within the specified MPU Protected Zone have been terminated successfully.
887 - \em osErrorParameter: \a zone is invalid.
888 - \em osErrorResource: no other \ref ThreadStates "READY" thread exists.
889 - \em osErrorISR: the function \b osThreadTerminateZone is called from interrupt other than fault.
890 - \em osError: the function \b osThreadTerminateZone is called from thread.
892 \note \b osThreadTerminateZone destroys non-joinable threads and removes their thread IDs from the system. Subsequent access to a terminated thread via its thread ID (for example \ref osThreadGetState) will return an \ref osThreadError. Joinable threads will not be destroyed and return the status \ref osThreadTerminated until they are joined with \ref osThreadJoin.
896 #include "cmsis_os2.h"
898 void TerminateFaultedThreads (void) { // to be called from an exception fault context
901 status = osThreadTerminateZone(3U); // Terminates threads assigned to MPU Protected Zone 3
902 // verify status value here.
907 /*=======0=========1=========2=========3=========4=========5=========6=========7=========8=========9=========0=========1====*/
909 \fn osStatus_t osThreadSetAffinityMask (osThreadId_t thread_id, uint32_t affinity_mask);
911 The function \b osThreadSetAffinityMask sets the affinity mask of the thread specified by parameter \a thread_id to the mask specified by the parameter \a affinity_mask.
912 The mask indicates on which processor(s) the thread should run (\token{0} indicates on any processor).
914 Possible \ref osStatus_t return values:
915 - \em osOK: the affinity mask of the specified thread has been set successfully.
916 - \em osErrorParameter: \a thread_id is \token{NULL} or invalid or \a priority is incorrect.
917 - \em osErrorResource: the thread is in an invalid state.
918 - \em osErrorISR: the function \b osThreadSetAffinityMask cannot be called from interrupt service routines.
919 - \em osErrorSafetyClass: the calling thread safety class is lower than the safety class of the specified thread.
921 \note This function \b cannot be called from \ref CMSIS_RTOS_ISR_Calls "Interrupt Service Routines".
925 #include "cmsis_os2.h"
927 void Thread_1 (void const *arg) { // Thread function
928 osThreadId_t id; // id for the currently running thread
929 osStatus_t status; // status of the executed function
931 id = osThreadGetId(); // Obtain ID of current running thread
933 status = osThreadSetAffinityMask(id, osThreadProcessor(1)); // Set thread affinity mask
934 if (status == osOK) {
935 // Thread affinity mask set to processor number 1
938 // Failed to set the affinity mask
944 /*=======0=========1=========2=========3=========4=========5=========6=========7=========8=========9=========0=========1====*/
946 \fn uint32_t osThreadGetAffinityMask (osThreadId_t thread_id);
948 The function \b osThreadGetAffinityMask returns the affinity mask of the thread specified by parameter \a thread_id.
949 In case of an error, it returns \token{0}.
951 \note This function \b cannot be called from \ref CMSIS_RTOS_ISR_Calls "Interrupt Service Routines".
955 #include "cmsis_os2.h"
957 void Thread_1 (void const *arg) { // Thread function
958 osThreadId_t id; // id for the currently running thread
959 uint32_t affinity_mask; // thread affinity mask
961 id = osThreadGetId(); // Obtain ID of current running thread
962 affinity_mask = osThreadGetAffinityMask(id); // Obtain the thread affinity mask
967 /*=======0=========1=========2=========3=========4=========5=========6=========7=========8=========9=========0=========1====*/
969 \fn uint32_t osWatchdogAlarm_Handler (osThreadId_t thread_id);
971 The callback function \b osWatchdogAlarm_Handler is called by the kernel when a thread watchdog expires.
972 Parameter \a thread_id identifies the thread which has the expired thread watchdog.
973 The function needs to be implemented in user application.
975 Return new reload value to restart the watchdog. Return \token{0} to stop the thread watchdog.
977 \note The callback function is called from interrupt.
980 When multiple watchdogs expire in the same tick, this function is called for each thread with highest safety class first.
984 #include "cmsis_os2.h"
986 uint32_t osWatchdogAlarm_Handler (osThreadId_t thread_id) {
987 uint32_t safety_class;
988 uint32_t next_interval;
990 safety_class = osThreadGetClass(thread_id);
992 /* Handle the watchdog depending on how safety-critical is the thread */
993 if (safety_class < ...){
999 return next_interval;
1004 /*=======0=========1=========2=========3=========4=========5=========6=========7=========8=========9=========0=========1====*/
1006 \fn void osZoneSetup_Callback (uint32_t zone);
1008 The callback function \b osZoneSetup_Callback is called by the kernel when MPU Protected Zone changes.
1009 The function shall be implemented in user application.
1011 <b>Code Example:</b>
1013 /* Update MPU settings for newly activating Zone */
1014 void osZoneSetup_Callback (uint32_t zone) {
1016 if (zone >= ZONES_NUM) {
1017 //Issue an error for incorrect zone value
1021 ARM_MPU_Load(mpu_table[zone], MPU_REGIONS);
1022 ARM_MPU_Enable(MPU_CTRL_PRIVDEFENA_Msk);
1026 \c ZONES_NUM is the total amount of zones allocated by the application.
1027 For \c ARM_MPU_... functions refer to <a href="../../Core/html/group__mpu__functions.html"><b>MPU Functions</b></a> in CMSIS-Core documentation.
1033 // these struct members must stay outside the group to avoid double entries in documentation
1036 \var osThreadAttr_t::attr_bits
1038 The following bit masks can be used to set options:
1039 - \ref osThreadDetached : create thread in a detached mode (default).
1040 - \ref osThreadJoinable : create thread in \ref joinable_threads "joinable mode".
1041 - \ref osThreadUnprivileged : create thread to execute in unprivileged mode.
1042 - \ref osThreadPrivileged : create thread to execute in privileged mode.
1043 - \ref osThreadZone (m) : create thread assigned to MPU zone \token{m}.
1044 - \ref osSafetyClass (n) : create thread with safety class \token{n} assigned to it.
1046 Default: \token{0} no options set. Safety class and MPU Zone are inherited from running thread. Thread privilege mode is set based on configuration \ref threadConfig_procmode.
1048 \var osThreadAttr_t::cb_mem
1050 Pointer to a memory for the thread control block object. Refer to \ref CMSIS_RTOS_MemoryMgmt_Manual for more information.
1052 Default: \token{NULL} to use \ref CMSIS_RTOS_MemoryMgmt_Automatic for the thread control block.
1054 \var osThreadAttr_t::cb_size
1056 The size (in bytes) of memory block passed with \ref cb_mem. Required value depends on the underlying kernel implementation.
1058 Default: \token{0} as the default is no memory provided with \ref cb_mem.
1060 \var osThreadAttr_t::name
1062 Pointer to a constant string with a human readable name (displayed during debugging) of the thread object.
1064 Default: \token{NULL} no name specified (debugger may display function name instead).
1066 \var osThreadAttr_t::priority
1068 Specifies the initial thread priority with a value from #osPriority_t.
1070 Default: \token{osPriorityNormal}.
1072 \var osThreadAttr_t::stack_mem
1074 Pointer to a memory location for the thread stack (64-bit aligned).
1076 Default: \token{NULL} - the memory for the stack is provided by the system based on the configuration of underlying RTOS kernel .
1078 \var osThreadAttr_t::stack_size
1080 The size (in bytes) of the stack specified by \ref stack_mem.
1082 Default: \token{0} as the default is no memory provided with \ref stack_mem.
1084 \var osThreadAttr_t::tz_module
1087 TrustZone Thread Context Management Identifier to allocate context memory for threads. The RTOS kernel that runs in
1088 non-secure state calls the interface functions defined by the header file TZ_context.h. Can safely be set to zero
1089 for threads not using secure calls at all.
1090 See <a href="../../Core/html/group__context__trustzone__functions.html">TrustZone RTOS Context Management</a>.
1092 Default: \token{0} not thread context specified.
1094 Applicable only for devices on Armv8-M architecture. Ignored on others.
1097 \var osThreadAttr_t::affinity_mask
1099 The affinity mask specified by \ref osThreadProcessor macro (multiple processors can be specified by OR-ing macros).
1101 Default: \token{0} to run on any processor.