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.
352 The preprocessor macro \b osThreadZone constructs attribute bitmask with MPU zone bits set to \a n.
356 /* ThreadB thread attributes */
357 const osThreadAttr_t thread_B_attr = {
358 .name = "ThreadB", // human readable thread name
359 .attr_bits = osThreadZone(3U) // assign thread to MPU zone 3
364 /*=======0=========1=========2=========3=========4=========5=========6=========7=========8=========9=========0=========1====*/
366 \def osThreadProcessor(n)
367 \param n processor number, starting with n=0 for processor #0. The number of supported processors depend on the hardware.
370 The preprocessor macro \b osThreadProcessor constructs the value for the osThreadAttr_t::affinity_mask derived from \a n.
374 /*=======0=========1=========2=========3=========4=========5=========6=========7=========8=========9=========0=========1====*/
376 \fn osThreadId_t osThreadNew (osThreadFunc_t func, void *argument, const osThreadAttr_t *attr)
378 The function \b osThreadNew starts a thread function by adding it to the list of active threads and sets it to state
379 \ref ThreadStates "READY". Arguments for the thread function are passed using the parameter pointer \a *argument. When the priority of the
380 created thread function is higher than the current \ref ThreadStates "RUNNING" thread, the created thread function starts instantly and
381 becomes the new \ref ThreadStates "RUNNING" thread. Thread attributes are defined with the parameter pointer \a attr. Attributes include
382 settings for thread priority, stack size, or memory allocation.
384 The function can be safely called before the RTOS is
385 started (call to \ref osKernelStart), but not before it is initialized (call to \ref osKernelInitialize).
387 The function \b osThreadNew returns the pointer to the thread object identifier or \token{NULL} in case of an error.
389 \note Cannot be called from \ref CMSIS_RTOS_ISR_Calls "Interrupt Service Routines".
393 Refer to the \ref thread_examples "Thread Examples" section.
396 /*=======0=========1=========2=========3=========4=========5=========6=========7=========8=========9=========0=========1====*/
398 \fn const char *osThreadGetName (osThreadId_t thread_id)
400 The function \b osThreadGetName returns the pointer to the name string of the thread identified by parameter \a thread_id or
401 \token{NULL} in case of an error.
403 \note This function may be called from \ref CMSIS_RTOS_ISR_Calls "Interrupt Service Routines".
407 void ThreadGetName_example (void) {
408 osThreadId_t thread_id = osThreadGetId();
409 const char* name = osThreadGetName(thread_id);
411 // Failed to get the thread name; not in a thread
417 /*=======0=========1=========2=========3=========4=========5=========6=========7=========8=========9=========0=========1====*/
419 \fn uint32_t osThreadGetClass (osThreadId_t thread_id);
421 The function \b osThreadGetClass returns safety class assigned to the thread identified by parameter \a thread_id. In case of an
422 error, it returns \ref osErrorId.
425 /*=======0=========1=========2=========3=========4=========5=========6=========7=========8=========9=========0=========1====*/
427 \fn uint32_t osThreadGetZone (osThreadId_t thread_id);
429 The function \b osThreadGetZone returns the MPU Protected Zone value assigned to the thread identified by parameter \a thread_id.
430 In case of an error, it returns \ref osErrorId.
433 /*=======0=========1=========2=========3=========4=========5=========6=========7=========8=========9=========0=========1====*/
435 \fn osThreadId_t osThreadGetId (void)
437 The function \b osThreadGetId returns the thread object ID of the currently running thread or NULL in case of an error.
439 \note This function may be called from \ref CMSIS_RTOS_ISR_Calls "Interrupt Service Routines".
443 void ThreadGetId_example (void) {
444 osThreadId_t id; // id for the currently running thread
446 id = osThreadGetId();
448 // Failed to get the id
453 /*=======0=========1=========2=========3=========4=========5=========6=========7=========8=========9=========0=========1====*/
455 \fn osThreadState_t osThreadGetState (osThreadId_t thread_id)
457 The function \b osThreadGetState returns the state of the thread identified by parameter \a thread_id. In case it fails or
458 if it is called from an ISR, it will return \c osThreadError, otherwise it returns the thread state (refer to
459 \ref osThreadState_t for the list of thread states).
461 \note This function \b cannot be called from \ref CMSIS_RTOS_ISR_Calls "Interrupt Service Routines".
464 /*=======0=========1=========2=========3=========4=========5=========6=========7=========8=========9=========0=========1====*/
466 \fn osStatus_t osThreadSetPriority (osThreadId_t thread_id, osPriority_t priority)
468 The function \b osThreadSetPriority changes the priority of an active thread specified by the parameter \a thread_id to the
469 priority specified by the parameter \a priority.
471 Possible \ref osStatus_t return values:
472 - \em osOK: the priority of the specified thread has been changed successfully.
473 - \em osErrorParameter: \a thread_id is \token{NULL} or invalid or \a priority is incorrect.
474 - \em osErrorResource: the thread is in an invalid state.
475 - \em osErrorISR: the function \b osThreadSetPriority cannot be called from interrupt service routines.
476 - \em osErrorSafetyClass: the calling thread safety class is lower than the safety class of the specified thread.
478 \note This function \b cannot be called from \ref CMSIS_RTOS_ISR_Calls "Interrupt Service Routines".
482 #include "cmsis_os2.h"
484 void Thread_1 (void const *arg) { // Thread function
485 osThreadId_t id; // id for the currently running thread
486 osStatus_t status; // status of the executed function
489 id = osThreadGetId(); // Obtain ID of current running thread
491 status = osThreadSetPriority(id, osPriorityBelowNormal); // Set thread priority
492 if (status == osOK) {
493 // Thread priority changed to BelowNormal
496 // Failed to set the priority
502 /*=======0=========1=========2=========3=========4=========5=========6=========7=========8=========9=========0=========1====*/
504 \fn osPriority_t osThreadGetPriority (osThreadId_t thread_id)
506 The function \b osThreadGetPriority returns the priority of an active thread specified by the parameter \a thread_id.
508 Possible \ref osPriority_t return values:
509 - \em priority: the priority of the specified thread.
510 - \em osPriorityError: priority cannot be determined or is illegal. It is also returned when the function is called from
511 \ref CMSIS_RTOS_ISR_Calls "Interrupt Service Routines".
513 \note This function \b cannot be called from \ref CMSIS_RTOS_ISR_Calls "Interrupt Service Routines".
517 #include "cmsis_os2.h"
519 void Thread_1 (void const *arg) { // Thread function
520 osThreadId_t id; // id for the currently running thread
521 osPriority_t priority; // thread priority
523 id = osThreadGetId(); // Obtain ID of current running thread
524 priority = osThreadGetPriority(id); // Obtain the thread priority
528 /*=======0=========1=========2=========3=========4=========5=========6=========7=========8=========9=========0=========1====*/
530 \fn osStatus_t osThreadYield (void)
532 The function \b osThreadYield passes control to the next thread with the same priority that is in the \ref ThreadStates "READY" state.
533 If there is no other thread with the same priority in state \ref ThreadStates "READY", then the current thread continues execution and
534 no thread switch occurs. \b osThreadYield does not set the thread to state \ref ThreadStates "BLOCKED". Thus no thread with a lower
535 priority will be scheduled even if threads in state \ref ThreadStates "READY" are available.
537 Possible \ref osStatus_t return values:
538 - \em osOK: control has been passed to the next thread successfully.
539 - \em osError: an unspecified error has occurred.
540 - \em osErrorISR: the function \b osThreadYield cannot be called from interrupt service routines.
542 \note This function \b cannot be called from \ref CMSIS_RTOS_ISR_Calls "Interrupt Service Routines".
543 \note This function <b>has no impact</b> when called when the kernel is locked, see \ref osKernelLock.
547 #include "cmsis_os2.h"
549 void Thread_1 (void const *arg) { // Thread function
550 osStatus_t status; // status of the executed function
553 status = osThreadYield();
554 if (status != osOK) {
561 /*=======0=========1=========2=========3=========4=========5=========6=========7=========8=========9=========0=========1====*/
563 \fn osStatus_t osThreadSuspend (osThreadId_t thread_id)
565 The function \b osThreadSuspend suspends the execution of the thread identified by parameter \em thread_id. The thread is put
566 into the \ref ThreadStates "BLOCKED" state (\ref osThreadBlocked). Suspending the running thread will cause a context switch to another
567 thread in \ref ThreadStates "READY" state immediately. The suspended thread is not executed until explicitly resumed with the function \ref osThreadResume.
569 Threads that are already \ref ThreadStates "BLOCKED" are removed from any wait list and become ready when they are resumed.
570 Thus it is not recommended to suspend an already blocked thread.
572 Possible \ref osStatus_t return values:
573 - \em osOK: the thread has been suspended successfully.
574 - \em osErrorParameter: \a thread_id is \token{NULL} or invalid.
575 - \em osErrorResource: the thread is in an invalid state.
576 - \em osErrorISR: the function \b osThreadSuspend cannot be called from interrupt service routines.
577 - \em osErrorSafetyClass: the calling thread safety class is lower than the safety class of the specified thread.
579 \note This function \b cannot be called from \ref CMSIS_RTOS_ISR_Calls "Interrupt Service Routines".
580 \note This function <b>must not</b> be called to suspend the running thread when the kernel is locked, i.e. \ref osKernelLock.
584 /*=======0=========1=========2=========3=========4=========5=========6=========7=========8=========9=========0=========1====*/
586 \fn osStatus_t osThreadResume (osThreadId_t thread_id)
588 The function \b osThreadResume puts the thread identified by parameter \em thread_id (which has to be in \ref ThreadStates "BLOCKED" state)
589 back to the \ref ThreadStates "READY" state. If the resumed thread has a higher priority than the running thread a context switch occurs immediately.
591 The thread becomes ready regardless of the reason why the thread was blocked. Thus it is not recommended to resume a thread not suspended
592 by \ref osThreadSuspend.
594 Functions that will put a thread into \ref ThreadStates "BLOCKED" state are:
595 \ref osEventFlagsWait and \ref osThreadFlagsWait,
596 \ref osDelay and \ref osDelayUntil,
597 \ref osMutexAcquire and \ref osSemaphoreAcquire,
598 \ref osMessageQueueGet,
599 \ref osMemoryPoolAlloc,
601 \ref osThreadSuspend.
603 Possible \ref osStatus_t return values:
604 - \em osOK: the thread has been resumed successfully.
605 - \em osErrorParameter: \a thread_id is \token{NULL} or invalid.
606 - \em osErrorResource: the thread is in an invalid state.
607 - \em osErrorISR: the function \b osThreadResume cannot be called from interrupt service routines.
608 - \em osErrorSafetyClass: the calling thread safety class is lower than the safety class of the specified thread.
610 \note This function \b cannot be called from \ref CMSIS_RTOS_ISR_Calls "Interrupt Service Routines".
611 \note This function <b>may be</b> called when kernel is locked (\ref osKernelLock). Under this circumstances
612 a potential context switch is delayed until the kernel gets unlocked, i.e. \ref osKernelUnlock or \ref osKernelRestoreLock.
616 /*=======0=========1=========2=========3=========4=========5=========6=========7=========8=========9=========0=========1====*/
618 \fn osStatus_t osThreadDetach (osThreadId_t thread_id)
620 The function \b osThreadDetach changes the attribute of a thread (specified by \em thread_id) to \ref osThreadDetached.
621 Detached threads are not joinable with \ref osThreadJoin. When a detached thread is terminated, all resources are returned to
622 the system. The behavior of \ref osThreadDetach on an already detached thread is undefined.
624 Possible \ref osStatus_t return values:
625 - \em osOK: the attribute of the specified thread has been changed to detached successfully.
626 - \em osErrorParameter: \a thread_id is \token{NULL} or invalid.
627 - \em osErrorResource: the thread is in an invalid state.
628 - \em osErrorISR: the function \b osThreadDetach cannot be called from interrupt service routines.
629 - \em osErrorSafetyClass: the calling thread safety class is lower than the safety class of the specified thread.
631 \note This function \b cannot be called from \ref CMSIS_RTOS_ISR_Calls "Interrupt Service Routines".
634 /*=======0=========1=========2=========3=========4=========5=========6=========7=========8=========9=========0=========1====*/
636 \fn osStatus_t osThreadJoin (osThreadId_t thread_id)
638 The function \b osThreadJoin waits for the thread specified by \em thread_id to terminate. If that thread has already
639 terminated, then \ref osThreadJoin returns immediately. The thread must be joinable. By default threads are created with the
640 attribute \ref osThreadDetached.
642 Possible \ref osStatus_t return values:
643 - \em osOK: if the thread has already been terminated and joined or once the thread has been terminated and the join
645 - \em osErrorParameter: \a thread_id is \token{NULL} or invalid.
646 - \em osErrorResource: the thread is in an invalid state (ex: not joinable).
647 - \em osErrorISR: the function \b osThreadJoin cannot be called from interrupt service routines.
648 - \em osErrorSafetyClass: the calling thread safety class is lower than the safety class of the specified thread.
650 \note This function \b cannot be called from \ref CMSIS_RTOS_ISR_Calls "Interrupt Service Routines". <br>
651 \note Only one thread shall call \b osThreadJoin to join the target thread. If multiple threads try to join simultaneously with the same thread,
652 the results are undefined.
656 /*=======0=========1=========2=========3=========4=========5=========6=========7=========8=========9=========0=========1====*/
658 \fn __NO_RETURN void osThreadExit (void)
661 The function \b osThreadExit terminates the calling thread. This allows the thread to be synchronized with \ref osThreadJoin.
663 \note This function \b cannot be called from \ref CMSIS_RTOS_ISR_Calls "Interrupt Service Routines".
667 __NO_RETURN void worker (void *argument) {
675 /*=======0=========1=========2=========3=========4=========5=========6=========7=========8=========9=========0=========1====*/
677 \fn osStatus_t osThreadTerminate (osThreadId_t thread_id)
679 The function \b osThreadTerminate removes the thread specified by parameter \a thread_id from the list of active threads. If
680 the thread is currently \ref ThreadStates "RUNNING", the thread terminates and the execution continues with the next \ref ThreadStates "READY" thread. If no
681 such thread exists, the function will not terminate the running thread, but return \em osErrorResource.
683 Possible \ref osStatus_t return values:
684 - \em osOK: the specified thread has been removed from the active thread list successfully.
685 - \em osErrorParameter: \a thread_id is \token{NULL} or invalid.
686 - \em osErrorResource: the thread is in an invalid state or no other \ref ThreadStates "READY" thread exists.
687 - \em osErrorISR: the function \b osThreadTerminate cannot be called from interrupt service routines.
688 - \em osErrorSafetyClass: the calling thread safety class is lower than the safety class of the specified thread.
690 \note This function \b cannot be called from \ref CMSIS_RTOS_ISR_Calls "Interrupt Service Routines".
691 \note Avoid calling the function with a \em thread_id that does not exist or has been terminated already.
692 \note \b osThreadTerminate destroys non-joinable threads and removes their thread_id from the system. Subsequent access to the
693 thread_id (for example \ref osThreadGetState) will return an \ref osThreadError. Joinable threads will not be destroyed and
694 return the status \ref osThreadTerminated until they are joined with \ref osThreadJoin.
698 #include "cmsis_os2.h"
700 void Thread_1 (void *arg); // function prototype for Thread_1
702 void ThreadTerminate_example (void) {
706 id = osThreadNew(Thread_1, NULL, NULL); // create the thread
708 status = osThreadTerminate(id); // stop the thread
709 if (status == osOK) {
710 // Thread was terminated successfully
713 // Failed to terminate a thread
719 /*=======0=========1=========2=========3=========4=========5=========6=========7=========8=========9=========0=========1====*/
721 \fn uint32_t osThreadGetStackSize (osThreadId_t thread_id)
723 The function \b osThreadGetStackSize returns the stack size of the thread specified by parameter \a thread_id. In case of an
724 error, it returns \token{0}.
726 \note This function \b cannot be called from \ref CMSIS_RTOS_ISR_Calls "Interrupt Service Routines".
729 /*=======0=========1=========2=========3=========4=========5=========6=========7=========8=========9=========0=========1====*/
731 \fn uint32_t osThreadGetStackSpace (osThreadId_t thread_id);
733 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}.
735 \note This function \b cannot be called from \ref CMSIS_RTOS_ISR_Calls "Interrupt Service Routines".
738 /*=======0=========1=========2=========3=========4=========5=========6=========7=========8=========9=========0=========1====*/
740 \fn uint32_t osThreadGetCount (void)
742 The function \b osThreadGetCount returns the number of active threads or \token{0} in case of an error.
744 \note This function \b cannot be called from \ref CMSIS_RTOS_ISR_Calls "Interrupt Service Routines".
747 /*=======0=========1=========2=========3=========4=========5=========6=========7=========8=========9=========0=========1====*/
749 \fn uint32_t osThreadEnumerate (osThreadId_t *thread_array, uint32_t array_items)
751 The function \b osThreadEnumerate returns the number of enumerated threads or \token{0} in case of an error.
753 \note This function \b cannot be called from \ref CMSIS_RTOS_ISR_Calls "Interrupt Service Routines".
756 /*=======0=========1=========2=========3=========4=========5=========6=========7=========8=========9=========0=========1====*/
758 \fn osStatus_t osThreadFeedWatchdog (uint32_t ticks);
760 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.
762 Possible \ref osStatus_t return values:
763 - \em osOK: the watchdog timer was restarted successfully.
764 - \em osError: cannot be executed (kernel not running).
765 - \em osErrorISR: the function \b osThreadFeedWatchdog cannot be called from interrupt service routines.
767 \note This function \b cannot be called from \ref CMSIS_RTOS_ISR_Calls "Interrupt Service Routines".
771 #include "cmsis_os2.h"
773 void Thread_1 (void const *arg) { // Thread function
774 osStatus_t status; // Status of the executed function
777 status = osThreadFeedWatchdog(500U); // Feed thread watchdog for 500 ticks
778 // verify status value here
785 /*=======0=========1=========2=========3=========4=========5=========6=========7=========8=========9=========0=========1====*/
787 \fn osStatus_t osThreadProtectPrivileged (void);
789 The function \b osThreadProtectPrivileged disables creation of new privileged threads. After its successful execution, no new
790 threads with privilege execution mode (\ref osThreadPrivileged attribute) can be created.
791 Kernel shall be in ready state or running when \b osThreadProtectPrivileged is called.
793 Possible \ref osStatus_t return values:
794 - \em osOK: the creation of new privileged threads is disabled.
795 - \em osError: cannot be executed (kernel not ready).
796 - \em osErrorISR: the function \b osThreadProtectPrivileged cannot be called from interrupt service routines.
798 \note This function \b cannot be called from \ref CMSIS_RTOS_ISR_Calls "Interrupt Service Routines".
802 #include "cmsis_os2.h"
807 status = osKernelInitialize(); // Initialize CMSIS-RTOS2 kernel
808 // verify status value here.
809 : // Create privileged threads
810 status = osThreadProtectPrivileged(); // Disable creation of new privileged threads.
811 // verify status value here.
812 : // Start the kernel
817 /*=======0=========1=========2=========3=========4=========5=========6=========7=========8=========9=========0=========1====*/
819 \fn osStatus_t osThreadSuspendClass (uint32_t safety_class, uint32_t mode);
821 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.
823 If \ref osSafetyWithSameClass is set in \a mode than the threads with safety class value equal to \a safety_class will be suspended.
825 If \ref osSafetyWithLowerClass is set in \a mode than the threads with safety class value lower than \a safety_class will be suspended.
827 Possible \ref osStatus_t return values:
828 - \em osOK: the threads with specified safety class have been suspended successfully.
829 - \em osErrorParameter: \a safety_class is invalid.
830 - \em osErrorResource: no other \ref ThreadStates "READY" thread exists.
831 - \em osErrorISR: the function \b osThreadSuspendClass is called from interrupt other than \ref osWatchdogAlarm_Handler.
832 - \em osErrorSafetyClass: the calling thread safety class is lower than the safety class specified by \a safety_class and \a mode.
836 #include "cmsis_os2.h"
838 void SuspendNonCriticalClasses (void) {
841 status = osThreadSuspendClass(4U, osSafetyWithSameClass | osSafetyWithLowerClass); // Suspends threads with safety class 4 or lower
842 // verify status value here.
847 /*=======0=========1=========2=========3=========4=========5=========6=========7=========8=========9=========0=========1====*/
849 \fn osStatus_t osThreadResumeClass (uint32_t safety_class, uint32_t mode);
851 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.
853 If \ref osSafetyWithSameClass is set in \a mode than the threads with safety class value equal to \a safety_class will be resumed.
855 If \ref osSafetyWithLowerClass is set in \a mode than the threads with safety class value lower than \a safety_class will be resumed.
858 Possible \ref osStatus_t return values:
859 - \em osOK: the threads with specified safety class have been resumed successfully.
860 - \em osErrorParameter: \a safety_class is invalid.
861 - \em osErrorISR: the function \b osThreadResumeClass is called from interrupt other than \ref osWatchdogAlarm_Handler.
862 - \em osErrorSafetyClass: the calling thread safety class is lower than the safety class specified by \a safety_class and \a mode.
866 #include "cmsis_os2.h"
868 void ResumeNonCriticalClasses (void) {
871 status = osThreadResumeClass(4U, osSafetyWithSameClass | osSafetyWithLowerClass); // Resumes threads with safety class 4 or lower
872 // verify status value here.
877 /*=======0=========1=========2=========3=========4=========5=========6=========7=========8=========9=========0=========1====*/
879 \fn osStatus_t osThreadTerminateZone (uint32_t zone);
881 The function \b osThreadTerminateZone terminates execution of threads assigned to the MPU Protected Zone as given by \a zone parameter.
883 Possible \ref osStatus_t return values:
884 - \em osOK: the threads within the specified MPU Protected Zone have been terminated successfully.
885 - \em osErrorParameter: \a zone is invalid.
886 - \em osErrorResource: no other \ref ThreadStates "READY" thread exists.
887 - \em osErrorISR: the function \b osThreadTerminateZone is called from interrupt other than fault.
888 - \em osError: the function \b osThreadTerminateZone is called from thread.
890 \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.
894 #include "cmsis_os2.h"
896 void TerminateFaultedThreads (void) { // to be called from an exception fault context
899 status = osThreadTerminateZone(3U); // Terminates threads assigned to MPU Protected Zone 3
900 // verify status value here.
905 /*=======0=========1=========2=========3=========4=========5=========6=========7=========8=========9=========0=========1====*/
907 \fn osStatus_t osThreadSetAffinityMask (osThreadId_t thread_id, uint32_t affinity_mask);
909 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.
910 The mask indicates on which processor(s) the thread should run (\token{0} indicates on any processor).
912 Possible \ref osStatus_t return values:
913 - \em osOK: the affinity mask of the specified thread has been set successfully.
914 - \em osErrorParameter: \a thread_id is \token{NULL} or invalid or \a affinity_mask is incorrect.
915 - \em osErrorResource: the thread is in an invalid state.
916 - \em osErrorISR: the function \b osThreadSetAffinityMask cannot be called from interrupt service routines.
917 - \em osErrorSafetyClass: the calling thread safety class is lower than the safety class of the specified thread.
919 \note This function \b cannot be called from \ref CMSIS_RTOS_ISR_Calls "Interrupt Service Routines".
923 #include "cmsis_os2.h"
925 void Thread_1 (void const *arg) { // Thread function
926 osThreadId_t id; // id for the currently running thread
927 osStatus_t status; // status of the executed function
929 id = osThreadGetId(); // Obtain ID of current running thread
931 status = osThreadSetAffinityMask(id, osThreadProcessor(1)); // run thread processor #1
932 if (status == osOK) {
933 // Thread affinity mask set to processor number 1
936 // Failed to set the affinity mask
942 /*=======0=========1=========2=========3=========4=========5=========6=========7=========8=========9=========0=========1====*/
944 \fn uint32_t osThreadGetAffinityMask (osThreadId_t thread_id);
946 The function \b osThreadGetAffinityMask returns the affinity mask of the thread specified by parameter \a thread_id.
947 In case of an error, it returns \token{0}.
949 \note This function \b cannot be called from \ref CMSIS_RTOS_ISR_Calls "Interrupt Service Routines".
953 #include "cmsis_os2.h"
955 void Thread_1 (void const *arg) { // Thread function
956 osThreadId_t id; // id for the currently running thread
957 uint32_t affinity_mask; // thread affinity mask
959 id = osThreadGetId(); // Obtain ID of current running thread
960 affinity_mask = osThreadGetAffinityMask(id); // Obtain the thread affinity mask
965 /*=======0=========1=========2=========3=========4=========5=========6=========7=========8=========9=========0=========1====*/
967 \fn uint32_t osWatchdogAlarm_Handler (osThreadId_t thread_id);
969 The callback function \b osWatchdogAlarm_Handler is called by the kernel when a thread watchdog expires.
970 Parameter \a thread_id identifies the thread which has the expired thread watchdog.
971 The function needs to be implemented in user application.
973 Return new reload value to restart the watchdog. Return \token{0} to stop the thread watchdog.
975 \note The callback function is called from interrupt.
978 When multiple watchdogs expire in the same tick, this function is called for each thread with highest safety class first.
982 #include "cmsis_os2.h"
984 uint32_t osWatchdogAlarm_Handler (osThreadId_t thread_id) {
985 uint32_t safety_class;
986 uint32_t next_interval;
988 safety_class = osThreadGetClass(thread_id);
990 /* Handle the watchdog depending on how safety-critical is the thread */
991 if (safety_class < ...){
997 return next_interval;
1002 /*=======0=========1=========2=========3=========4=========5=========6=========7=========8=========9=========0=========1====*/
1004 \fn void osZoneSetup_Callback (uint32_t zone);
1006 The callback function \b osZoneSetup_Callback is called by the kernel when MPU Protected Zone changes.
1007 The function shall be implemented in user application.
1009 <b>Code Example:</b>
1011 /* Update MPU settings for newly activating Zone */
1012 void osZoneSetup_Callback (uint32_t zone) {
1014 if (zone >= ZONES_NUM) {
1015 //Issue an error for incorrect zone value
1019 ARM_MPU_Load(mpu_table[zone], MPU_REGIONS);
1020 ARM_MPU_Enable(MPU_CTRL_PRIVDEFENA_Msk);
1024 \c ZONES_NUM is the total amount of zones allocated by the application.
1025 For \c ARM_MPU_... functions refer to <a href="../Core/group__mpu__functions.html"><b>MPU Functions</b></a> in CMSIS-Core documentation.
1031 // these struct members must stay outside the group to avoid double entries in documentation
1034 \var osThreadAttr_t::attr_bits
1036 The following bit masks can be used to set options:
1037 - \ref osThreadDetached : create thread in a detached mode (default).
1038 - \ref osThreadJoinable : create thread in \ref joinable_threads "joinable mode".
1039 - \ref osThreadUnprivileged : create thread to execute in unprivileged mode.
1040 - \ref osThreadPrivileged : create thread to execute in privileged mode.
1041 - \ref osThreadZone (m) : create thread assigned to MPU zone \token{m}.
1042 - \ref osSafetyClass (n) : create thread with safety class \token{n} assigned to it.
1044 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.
1046 \var osThreadAttr_t::cb_mem
1048 Pointer to a memory for the thread control block object. Refer to \ref CMSIS_RTOS_MemoryMgmt_Manual for more information.
1050 Default: \token{NULL} to use \ref CMSIS_RTOS_MemoryMgmt_Automatic for the thread control block.
1052 \var osThreadAttr_t::cb_size
1054 The size (in bytes) of memory block passed with \ref cb_mem. Required value depends on the underlying kernel implementation.
1056 Default: \token{0} as the default is no memory provided with \ref cb_mem.
1058 \var osThreadAttr_t::name
1060 Pointer to a constant string with a human readable name (displayed during debugging) of the thread object.
1062 Default: \token{NULL} no name specified (debugger may display function name instead).
1064 \var osThreadAttr_t::priority
1066 Specifies the initial thread priority with a value from #osPriority_t.
1068 Default: \token{osPriorityNormal}.
1070 \var osThreadAttr_t::stack_mem
1072 Pointer to a memory location for the thread stack (64-bit aligned).
1074 Default: \token{NULL} - the memory for the stack is provided by the system based on the configuration of underlying RTOS kernel .
1076 \var osThreadAttr_t::stack_size
1078 The size (in bytes) of the stack specified by \ref stack_mem.
1080 Default: \token{0} as the default is no memory provided with \ref stack_mem.
1082 \var osThreadAttr_t::tz_module
1085 TrustZone Thread Context Management Identifier to allocate context memory for threads. The RTOS kernel that runs in
1086 non-secure state calls the interface functions defined by the header file TZ_context.h. Can safely be set to zero
1087 for threads not using secure calls at all.
1088 See <a href="../Core/group__context__trustzone__functions.html">TrustZone RTOS Context Management</a>.
1090 Default: \token{0} not thread context specified.
1092 Applicable only for devices on Armv8-M architecture. Ignored on others.
1095 \var osThreadAttr_t::affinity_mask
1097 Use the \ref osThreadProcessor macro to create the mask value. Multiple processors can be specified by OR-ing values.
1099 Default: value \token{0} is RTOS implementation specific and may map to running on processor #0 or on any processor.