| CMSIS-RTOS2 Real-Time Operating System API |

Loading...
Searching...
No Matches
Data Structures | Macros | Typedefs | Enumerations | Functions
Thread Management
CMSIS-RTOS2 API

Define, create, and control thread functions. More...

## Data Structures
struct | osThreadAttr_t
| Attributes structure for thread. More...

## Macros
#define | osErrorId 0xFFFFFFFFU
| osError (-1).
#define | osThreadJoinable 0x00000001U
| Thread created in joinable mode.
#define | osThreadDetached 0x00000000U
| Thread created in detached mode (default)
#define | osThreadUnprivileged 0x00000002U
| Thread runs in unprivileged mode.
#define | osThreadPrivileged 0x00000004U
| Thread runs in privileged mode.
#define | osThreadZone(n)
| MPU zone value in attribute bit field format.
#define | osThreadProcessor(n) (1UL << (n))
| Thread processor number for SMP systems.

## Typedefs
typedef void(* | osThreadFunc_t) (void *argument)
| Entry point of a thread.
typedef void * | osThreadId_t

## Enumerations
enum | osThreadState_t { osThreadInactive = 0 , osThreadReady = 1 , osThreadRunning = 2 , osThreadBlocked = 3 , osThreadTerminated = 4 , osThreadError = -1 , osThreadReserved = 0x7FFFFFFF }
| Thread state. More...
enum | osPriority_t { osPriorityNone = 0 , osPriorityIdle = 1 , osPriorityLow = 8 , osPriorityLow1 = 8+1 , osPriorityLow2 = 8+2 , osPriorityLow3 = 8+3 , osPriorityLow4 = 8+4 , osPriorityLow5 = 8+5 , osPriorityLow6 = 8+6 , osPriorityLow7 = 8+7 , osPriorityBelowNormal = 16 , osPriorityBelowNormal1 = 16+1 , osPriorityBelowNormal2 = 16+2 , osPriorityBelowNormal3 = 16+3 , osPriorityBelowNormal4 = 16+4 , osPriorityBelowNormal5 = 16+5 , osPriorityBelowNormal6 = 16+6 , osPriorityBelowNormal7 = 16+7 , osPriorityNormal = 24 , osPriorityNormal1 = 24+1 , osPriorityNormal2 = 24+2 , osPriorityNormal3 = 24+3 , osPriorityNormal4 = 24+4 , osPriorityNormal5 = 24+5 , osPriorityNormal6 = 24+6 , osPriorityNormal7 = 24+7 , osPriorityAboveNormal = 32 , osPriorityAboveNormal1 = 32+1 , osPriorityAboveNormal2 = 32+2 , osPriorityAboveNormal3 = 32+3 , osPriorityAboveNormal4 = 32+4 , osPriorityAboveNormal5 = 32+5 , osPriorityAboveNormal6 = 32+6 , osPriorityAboveNormal7 = 32+7 , osPriorityHigh = 40 , osPriorityHigh1 = 40+1 , osPriorityHigh2 = 40+2 , osPriorityHigh3 = 40+3 , osPriorityHigh4 = 40+4 , osPriorityHigh5 = 40+5 , osPriorityHigh6 = 40+6 , osPriorityHigh7 = 40+7 , osPriorityRealtime = 48 , osPriorityRealtime1 = 48+1 , osPriorityRealtime2 = 48+2 , osPriorityRealtime3 = 48+3 , osPriorityRealtime4 = 48+4 , osPriorityRealtime5 = 48+5 , osPriorityRealtime6 = 48+6 , osPriorityRealtime7 = 48+7 , osPriorityISR = 56 , osPriorityError = -1 , osPriorityReserved = 0x7FFFFFFF }
| Priority values. More...

## Functions
osThreadId_t | osThreadNew (osThreadFunc_t func, void *argument, const osThreadAttr_t *attr)
| Create a thread and add it to Active Threads.
const char * | osThreadGetName (osThreadId_t thread_id)
| Get name of a thread.
uint32_t | osThreadGetClass (osThreadId_t thread_id)
| Get safety class of a thread.
uint32_t | osThreadGetZone (osThreadId_t thread_id)
| Get MPU protected zone of a thread.
osThreadId_t | osThreadGetId (void)
| Return the thread ID of the current running thread.
osThreadState_t | osThreadGetState (osThreadId_t thread_id)
| Get current thread state of a thread.
osStatus_t | osThreadSetPriority (osThreadId_t thread_id, osPriority_t priority)
| Change priority of a thread.
osPriority_t | osThreadGetPriority (osThreadId_t thread_id)
| Get current priority of a thread.
osStatus_t | osThreadYield (void)
| Pass control to next thread that is in state READY.
osStatus_t | osThreadSuspend (osThreadId_t thread_id)
| Suspend execution of a thread.
osStatus_t | osThreadResume (osThreadId_t thread_id)
| Resume execution of a thread.
osStatus_t | osThreadDetach (osThreadId_t thread_id)
| Detach a thread (thread storage can be reclaimed when thread terminates).
osStatus_t | osThreadJoin (osThreadId_t thread_id)
| Wait for specified thread to terminate.
__NO_RETURN void | osThreadExit (void)
| Terminate execution of current running thread.
osStatus_t | osThreadTerminate (osThreadId_t thread_id)
| Terminate execution of a thread.
uint32_t | osThreadGetStackSize (osThreadId_t thread_id)
| Get stack size of a thread.
uint32_t | osThreadGetStackSpace (osThreadId_t thread_id)
| Get available stack space of a thread based on stack watermark recording during execution.
uint32_t | osThreadGetCount (void)
| Get number of active threads.
uint32_t | osThreadEnumerate (osThreadId_t *thread_array, uint32_t array_items)
| Enumerate active threads.
osStatus_t | osThreadFeedWatchdog (uint32_t ticks)
| Feed watchdog of the current running thread.
osStatus_t | osThreadProtectPrivileged (void)
| Protect creation of privileged threads.
osStatus_t | osThreadSuspendClass (uint32_t safety_class, uint32_t mode)
| Suspend execution of threads for specified safety classes.
osStatus_t | osThreadResumeClass (uint32_t safety_class, uint32_t mode)
| Resume execution of threads for specified safety classes.
osStatus_t | osThreadTerminateZone (uint32_t zone)
| Terminate execution of threads assigned to a specified MPU protected zone.
osStatus_t | osThreadSetAffinityMask (osThreadId_t thread_id, uint32_t affinity_mask)
| Set processor affinity mask of a thread.
uint32_t | osThreadGetAffinityMask (osThreadId_t thread_id)
| Get current processor affinity mask of a thread.
uint32_t | osWatchdogAlarm_Handler (osThreadId_t thread_id)
| Handler for expired thread watchdogs.
void | osZoneSetup_Callback (uint32_t zone)
| Setup MPU protected zone (called when zone changes).

## Description

Define, create, and control thread functions.

The Thread Management function group allows defining, creating, and controlling thread functions in the system.

Note
  Thread management functions cannot be called from Interrupt Service Routines.

## Thread states

Threads can be in the following states:

- RUNNING: The thread that is currently running is in the RUNNING state. Only one thread at a time can be in this state.
- READY: Threads which are ready to run are in the READY state. Once the RUNNING thread has terminated, or is BLOCKED, the next READY thread with the highest priority becomes the RUNNING thread.
- BLOCKED: Threads that are blocked either delayed, waiting for an event to occur or suspended are in the BLOCKED state.
- TERMINATED: When osThreadTerminate is called, threads are TERMINATED with resources not yet released (applies to joinable threads).
- INACTIVE: Threads that are not created or have been terminated with all resources released are in the INACTIVE state.

Thread State and State Transitions

A CMSIS-RTOS assumes that threads are scheduled as shown in the figure Thread State and State Transitions. The thread states change as follows:

- A thread is created using the function osThreadNew. This puts the thread into the READY or RUNNING state (depending on the thread priority).
- CMSIS-RTOS is preemptive. The active thread with the highest priority becomes the RUNNING thread provided it does not wait for any event. The initial priority of a thread is defined with the osThreadAttr_t but may be changed during execution using the function osThreadSetPriority.
- The RUNNING thread transfers into the BLOCKED state when it is delayed, waiting for an event or suspended.
- Active threads can be terminated any time using the function osThreadTerminate. Threads can terminate also by just returning from the thread function. Threads that are terminated are in the INACTIVE state and typically do not consume any dynamic memory resources.

## Processor Mode for Thread Execution

When creating user threads with 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 osThreadPrivileged or osThreadUnprivileged set respectively. If not set then the default operation mode will be used according to kernel configuration.

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:

In unprivileged processor mode, the thread :

- has limited access to the MSR and MRS instructions, and cannot use the CPS instruction.
- cannot access the system timer, NVIC, or system control block.
- might have restricted access to memory or peripherals.

In privileged processor mode, the application software can use all the instructions and has access to all resources.

# Thread Examples

The following examples show various scenarios to create threads:

Example 1 - Create a simple thread

Create a thread out of the function thread1 using all default values for thread attributes and memory allocated by the system.

__NO_RETURN void thread1 (void *argument) {
// ...
for (;;) {}
}
int main (void) {
osKernelInitialize();
;
osThreadNew(thread1, NULL, NULL); // Create thread with default settings
;
osKernelStart();
}

Example 2 - Create thread with stack non-default stack size

Similar to the simple thread all attributes are default. The stack size is requested of size 1024 Bytes with with corresponding value passed as osThreadAttr_t::stack_size to osThreadNew. The memory for the stack is then allocated by the system.

__NO_RETURN void thread1 (void *argument) {
// ...
for (;;) {}
}
const osThreadAttr_t thread1_attr = {
.stack_size = 1024 // Create the thread stack with a size of 1024 bytes
};
int main (void) {
;
osThreadNew(thread1, NULL, &thread1_attr); // Create thread with custom sized stack memory
;
}

Example 3 - Create thread with statically allocated stack

Similar to the simple thread all attributes are default. The stack is statically allocated using the `uint64_t` array `thread1_stk_1`. This allocates 64*8 Bytes (=512 Bytes) with an alignment of 8 Bytes (mandatory for Cortex-M stack memory).

osThreadAttr_t::stack_mem holds a pointer to the stacks lowest address.

osThreadAttr_t::stack_size is used to pass the stack size in Bytes to osThreadNew.

__NO_RETURN void thread1 (void *argument) {
// ...
for (;;) {}
}
static uint64_t thread1_stk_1[64];
const osThreadAttr_t thread1_attr = {
.stack_mem = &thread1_stk_1[0],
.stack_size = sizeof(thread1_stk_1)
};
int main (void) {
;
osThreadNew(thread1, NULL, &thread1_attr); // Create thread with statically allocated stack memory
;
}

Example 4 - Thread with statically allocated task control block

Typically this method is chosen together with a statically allocated stack as shown in Example 2.

#include "cmsis_os2.h"
//include rtx_os.h for control blocks of CMSIS-RTX objects
#include "rtx_os.h"
__NO_RETURN void thread1 (void *argument) {
// ...
for (;;) {}
}
static osRtxThread_t thread1_tcb;
const osThreadAttr_t thread1_attr = {
.cb_mem = &thread1_tcb,
.cb_size = sizeof(thread1_tcb),
};
int main (void) {
;
osThreadNew(thread1, NULL, &thread1_attr); // Create thread with custom tcb memory
;
}

Example 5 - Create thread with a different priority

The default priority of RTX kernel is osPriorityNormal. Often you want to run a task with a higher or lower priority. Using the osThreadAttr_t::priority field you can assign any initial priority required.

__NO_RETURN void thread1 (void *argument) {
// ...
for (;;) {}
}
const osThreadAttr_t thread1_attr = {
.priority = osPriorityHigh //Set initial thread priority to high
};
int main (void) {
;
osThreadNew(thread1, NULL, &thread1_attr);
;
}

Example 6 - Joinable threads

In this example a master thread creates four threads with the osThreadJoinable attribute. These will do some work and return using the osThreadExit call after finished. osThreadJoin is used to synchronize the thread termination.

__NO_RETURN void worker (void *argument) {
; // work a lot on data[]
osDelay(1000U);
osThreadExit();
}
__NO_RETURN void thread1 (void *argument) {
osThreadAttr_t worker_attr;
osThreadId_t worker_ids[4];
uint8_t data[4][10];
memset(&worker_attr, 0, sizeof(worker_attr));
worker_attr.attr_bits = osThreadJoinable;
worker_ids[0] = osThreadNew(worker, &data[0][0], &worker_attr);
worker_ids[1] = osThreadNew(worker, &data[1][0], &worker_attr);
worker_ids[2] = osThreadNew(worker, &data[2][0], &worker_attr);
worker_ids[3] = osThreadNew(worker, &data[3][0], &worker_attr);
osThreadJoin(worker_ids[0]);
osThreadJoin(worker_ids[1]);
osThreadJoin(worker_ids[2]);
osThreadJoin(worker_ids[3]);
osThreadExit();
}

## Data Structure Documentation

## ◆ osThreadAttr_t

struct osThreadAttr_t

Attributes structure for thread.

Specifies the following attributes for the osThreadNew function.

Data Fields
const char * | name | name of the thread Pointer to a constant string with a human readable name (displayed during debugging) of the thread object. Default: NULL no name specified (debugger may display function name instead).
uint32_t | attr_bits | attribute bits The following bit masks can be used to set options: osThreadDetached : create thread in a detached mode (default). osThreadJoinable : create thread in joinable mode. osThreadUnprivileged : create thread to execute in unprivileged mode. osThreadPrivileged : create thread to execute in privileged mode. osThreadZone (m) : create thread assigned to MPU zone m. osSafetyClass (n) : create thread with safety class n assigned to it. Default: 0 no options set. Safety class and MPU Zone are inherited from running thread. Thread privilege mode is set based on configuration threadConfig_procmode.
void * | cb_mem | memory for control block Pointer to a memory for the thread control block object. Refer to Manual User-defined Allocation for more information. Default: NULL to use Automatic Dynamic Allocation for the thread control block.
uint32_t | cb_size | size of provided memory for control block The size (in bytes) of memory block passed with cb_mem. Required value depends on the underlying kernel implementation. Default: 0 as the default is no memory provided with cb_mem.
void * | stack_mem | memory for stack Pointer to a memory location for the thread stack (64-bit aligned). Default: NULL - the memory for the stack is provided by the system based on the configuration of underlying RTOS kernel .
uint32_t | stack_size | size of stack The size (in bytes) of the stack specified by stack_mem. Default: 0 as the default is no memory provided with stack_mem.
osPriority_t | priority | initial thread priority (default: osPriorityNormal) Specifies the initial thread priority with a value from osPriority_t. Default: osPriorityNormal.
TZ_ModuleId_t | tz_module | TrustZone module identifier. TrustZone Thread Context Management Identifier to allocate context memory for threads. The RTOS kernel that runs in non-secure state calls the interface functions defined by the header file TZ_context.h. Can safely be set to zero for threads not using secure calls at all. See TrustZone RTOS Context Management. Default: 0 not thread context specified.
uint32_t | affinity_mask | processor affinity mask for binding the thread to a CPU in a SMP system (0 when not used) Use the osThreadProcessor macro to create the mask value. Multiple processors can be specified by OR-ing values. Default: value 0 is RTOS implementation specific and may map to running on processor #0 or on any processor.

## Macro Definition Documentation

## ◆ osErrorId

#define osErrorId 0xFFFFFFFFU

osError (-1).

Error return code from osThreadGetClass and osThreadGetZone.

## ◆ osThreadJoinable

#define osThreadJoinable 0x00000001U

Thread created in joinable mode.

Bitmask for a thread that can be joined. Intended for use in attr_bits of osThreadAttr_t type argument for osThreadNew function.

A thread in this state can be joined using osThreadJoin.

## ◆ osThreadDetached

#define osThreadDetached 0x00000000U

Thread created in detached mode (default)

Bitmask for a thread that cannot be joined. Intended for use in attr_bits of osThreadAttr_t type argument for osThreadNew function.

A thread in this state cannot be joined using osThreadJoin.

## ◆ osThreadUnprivileged

#define osThreadUnprivileged 0x00000002U

Thread runs in unprivileged mode.

Bitmask for a thread that runs in unprivileged mode. Intended for use in attr_bits of osThreadAttr_t type argument for osThreadNew function.

In unprivileged processor mode, a thread:

- has limited access to the MSR and MRS instructions, and cannot use the CPS instruction.
- cannot access the system timer, NVIC, or system control block.
- might have restricted access to memory or peripherals.

Note
  Ignored on processors that only run in privileged mode.

Refer to the target processor User's Guide for details.

## ◆ osThreadPrivileged

#define osThreadPrivileged 0x00000004U

Thread runs in privileged mode.

Bitmask for a thread that runs in privileged mode. Intended for use in attr_bits of osThreadAttr_t type argument for osThreadNew function.

In privileged processor mode, the application software can use all the instructions and has access to all resources.

## ◆ osThreadZone

#define osThreadZone | ( |  | n | ) |

MPU zone value in attribute bit field format.

Parameters

  n | MPU Protected Zone value.

The preprocessor macro osThreadZone constructs attribute bitmask with MPU zone bits set to n.

Code Example:

/* ThreadB thread attributes */
const osThreadAttr_t thread_B_attr = {
.name = "ThreadB", // human readable thread name
.attr_bits = osThreadZone(3U) // assign thread to MPU zone 3
};

## ◆ osThreadProcessor

#define osThreadProcessor | ( |  | n | ) | (1UL << (n))

Thread processor number for SMP systems.

Parameters

  n | processor number, starting with n=0 for processor #0. The number of supported processors depend on the hardware.

The preprocessor macro osThreadProcessor constructs the value for the osThreadAttr_t::affinity_mask derived from n.

## Typedef Documentation

## ◆ osThreadFunc_t

void(* osThreadFunc_t)(void *argument)

Entry point of a thread.

Entry function for threads. Setting up a new thread (osThreadNew) will start execution with a call into this entry function. The optional argument can be used to hand over arbitrary user data to the thread, i.e. to identify the thread or for runtime parameters.

Parameters

  [in] | argument | arbitrary user data set on osThreadNew.

## ◆ osThreadId_t

osThreadId_t

Thread ID identifies the thread.

Returned by:

- osThreadNew
- osThreadGetId
- osThreadEnumerate
- osMutexGetOwner

## Enumeration Type Documentation

## ◆ osThreadState_t

enum osThreadState_t

Thread state.

State of a thread as retrieved by osThreadGetState. In case osThreadGetState fails or if it is called from an ISR, it will return `osThreadError`, otherwise it returns the thread state.

Enumerator
osThreadInactive | Inactive. The thread is created but not actively used, or has been terminated (returned for static control block allocation, when memory pools are used osThreadError is returned as the control block is no longer valid)
osThreadReady | Ready. The thread is ready for execution but not currently running.
osThreadRunning | Running. The thread is currently running.
osThreadBlocked | Blocked. The thread is currently blocked (delayed, waiting for an event or suspended).
osThreadTerminated | Terminated. The thread is terminated and all its resources are not yet freed (applies to joinable threads).
osThreadError | Error. The thread does not exist (has raised an error condition) and cannot be scheduled.

## ◆ osPriority_t

enum osPriority_t

Priority values.

The osPriority_t value specifies the priority for a thread. The default thread priority should be osPriorityNormal. If an active thread becomes ready that has a higher priority than the currently running thread then a thread switch occurs immediately. The system continues executing the thread with the higher priority.

To prevent from a priority inversion, a CMSIS-RTOS compliant OS may optionally implement a priority inheritance method. A priority inversion occurs when a high priority thread is waiting for a resource or event that is controlled by a thread with a lower priority. Thus causing the high priority thread potentially being blocked forever by another thread with lower priority. To come over this issue the low priority thread controlling the resource should be treated as having the higher priority until it releases the resource.

Note
  Priority inheritance only applies to mutexes.

Enumerator
osPriorityIdle | Reserved for Idle thread. This lowest priority should not be used for any other thread.
osPriorityISR | Reserved for ISR deferred thread. This highest priority might be used by the RTOS implementation but must not be used for any user thread.

## Function Documentation

## ◆ osThreadNew()

osThreadId_t osThreadNew | ( | osThreadFunc_t | func,
|  | void * | argument,
|  | const osThreadAttr_t * | attr
| ) |  |

Create a thread and add it to Active Threads.

Parameters

  [in] | func | thread function.
  [in] | argument | pointer that is passed to the thread function as start argument.
  [in] | attr | thread attributes; NULL: default values.

Returns
  thread ID for reference by other functions or NULL in case of error.

The function osThreadNew starts a thread function by adding it to the list of active threads and sets it to state READY. Arguments for the thread function are passed using the parameter pointer *argument. When the priority of the created thread function is higher than the current RUNNING thread, the created thread function starts instantly and becomes the new RUNNING thread. Thread attributes are defined with the parameter pointer attr. Attributes include settings for thread priority, stack size, or memory allocation.

The function can be safely called before the RTOS is started (call to osKernelStart), but not before it is initialized (call to osKernelInitialize).

The function osThreadNew returns the pointer to the thread object identifier or NULL in case of an error.

Note
  Cannot be called from Interrupt Service Routines.

Code Example

Refer to the Thread Examples section.

## ◆ osThreadGetName()

const char * osThreadGetName | ( | osThreadId_t | thread_id | ) |

Get name of a thread.

Parameters

  [in] | thread_id | thread ID obtained by osThreadNew or osThreadGetId.

Returns
  name as null-terminated string.

The function osThreadGetName returns the pointer to the name string of the thread identified by parameter thread_id or NULL in case of an error.

Note
  This function may be called from Interrupt Service Routines.

Code Example

void ThreadGetName_example (void) {
osThreadId_t thread_id = osThreadGetId();
const char* name = osThreadGetName(thread_id);
if (name == NULL) {
// Failed to get the thread name; not in a thread
}
}

## ◆ osThreadGetClass()

uint32_t osThreadGetClass | ( | osThreadId_t | thread_id | ) |

Get safety class of a thread.

Parameters

  [in] | thread_id | thread ID obtained by osThreadNew or osThreadGetId.

Returns
  safety class of the specified thread.

The function osThreadGetClass returns safety class assigned to the thread identified by parameter thread_id. In case of an error, it returns osErrorId.

## ◆ osThreadGetZone()

uint32_t osThreadGetZone | ( | osThreadId_t | thread_id | ) |

Get MPU protected zone of a thread.

Parameters

  [in] | thread_id | thread ID obtained by osThreadNew or osThreadGetId.

Returns
  MPU protected zone of the specified thread.

The function osThreadGetZone returns the MPU Protected Zone value assigned to the thread identified by parameter thread_id. In case of an error, it returns osErrorId.

## ◆ osThreadGetId()

osThreadId_t osThreadGetId | ( | void |  | ) |

Return the thread ID of the current running thread.

Returns
  thread ID for reference by other functions or NULL in case of error.

The function osThreadGetId returns the thread object ID of the currently running thread or NULL in case of an error.

Note
  This function may be called from Interrupt Service Routines.

Code Example

void ThreadGetId_example (void) {
osThreadId_t id; // id for the currently running thread
id = osThreadGetId();
if (id == NULL) {
// Failed to get the id
}
}

## ◆ osThreadGetState()

osThreadState_t osThreadGetState | ( | osThreadId_t | thread_id | ) |

Get current thread state of a thread.

Parameters

  [in] | thread_id | thread ID obtained by osThreadNew or osThreadGetId.

Returns
  current thread state of the specified thread.

The function osThreadGetState returns the state of the thread identified by parameter thread_id. In case it fails or if it is called from an ISR, it will return `osThreadError`, otherwise it returns the thread state (refer to osThreadState_t for the list of thread states).

Note
  This function cannot be called from Interrupt Service Routines.

## ◆ osThreadSetPriority()

osStatus_t osThreadSetPriority | ( | osThreadId_t | thread_id,
|  | osPriority_t | priority
| ) |  |

Change priority of a thread.

Parameters

  [in] | thread_id | thread ID obtained by osThreadNew or osThreadGetId.
  [in] | priority | new priority value for the thread function.

Returns
  status code that indicates the execution status of the function.

The function osThreadSetPriority changes the priority of an active thread specified by the parameter thread_id to the priority specified by the parameter priority.

Possible osStatus_t return values:

- osOK: the priority of the specified thread has been changed successfully.
- osErrorParameter: thread_id is NULL or invalid or priority is incorrect.
- osErrorResource: the thread is in an invalid state.
- osErrorISR: the function osThreadSetPriority cannot be called from interrupt service routines.
- osErrorSafetyClass: the calling thread safety class is lower than the safety class of the specified thread.

Note
  This function cannot be called from Interrupt Service Routines.

Code Example

#include "cmsis_os2.h"
void Thread_1 (void const *arg) { // Thread function
osThreadId_t id; // id for the currently running thread
osStatus_t status; // status of the executed function
:
id = osThreadGetId(); // Obtain ID of current running thread
status = osThreadSetPriority(id, osPriorityBelowNormal); // Set thread priority
if (status == osOK) {
// Thread priority changed to BelowNormal
}
else {
// Failed to set the priority
}
:
}

## ◆ osThreadGetPriority()

osPriority_t osThreadGetPriority | ( | osThreadId_t | thread_id | ) |

Get current priority of a thread.

Parameters

  [in] | thread_id | thread ID obtained by osThreadNew or osThreadGetId.

Returns
  current priority value of the specified thread.

The function osThreadGetPriority returns the priority of an active thread specified by the parameter thread_id.

Possible osPriority_t return values:

- priority: the priority of the specified thread.
- osPriorityError: priority cannot be determined or is illegal. It is also returned when the function is called from Interrupt Service Routines.

Note
  This function cannot be called from Interrupt Service Routines.

Code Example

#include "cmsis_os2.h"
void Thread_1 (void const *arg) { // Thread function
osThreadId_t id; // id for the currently running thread
osPriority_t priority; // thread priority
id = osThreadGetId(); // Obtain ID of current running thread
priority = osThreadGetPriority(id); // Obtain the thread priority
}

## ◆ osThreadYield()

osStatus_t osThreadYield | ( | void |  | ) |

Pass control to next thread that is in state READY.

Returns
  status code that indicates the execution status of the function.

The function osThreadYield passes control to the next thread with the same priority that is in the READY state. If there is no other thread with the same priority in state READY, then the current thread continues execution and no thread switch occurs. osThreadYield does not set the thread to state BLOCKED. Thus no thread with a lower priority will be scheduled even if threads in state READY are available.

Possible osStatus_t return values:

- osOK: control has been passed to the next thread successfully.
- osError: an unspecified error has occurred.
- osErrorISR: the function osThreadYield cannot be called from interrupt service routines.

Note
  This function cannot be called from Interrupt Service Routines.
  This function has no impact when called when the kernel is locked, see osKernelLock.

Code Example

#include "cmsis_os2.h"
void Thread_1 (void const *arg) { // Thread function
osStatus_t status; // status of the executed function
:
while (1) {
status = osThreadYield();
if (status != osOK) {
// an error occurred
}
}
}

## ◆ osThreadSuspend()

osStatus_t osThreadSuspend | ( | osThreadId_t | thread_id | ) |

Suspend execution of a thread.

Parameters

  [in] | thread_id | thread ID obtained by osThreadNew or osThreadGetId.

Returns
  status code that indicates the execution status of the function.

The function osThreadSuspend suspends the execution of the thread identified by parameter thread_id. The thread is put into the BLOCKED state (osThreadBlocked). Suspending the running thread will cause a context switch to another thread in READY state immediately. The suspended thread is not executed until explicitly resumed with the function osThreadResume.

Threads that are already BLOCKED are removed from any wait list and become ready when they are resumed. Thus it is not recommended to suspend an already blocked thread.

Possible osStatus_t return values:

- osOK: the thread has been suspended successfully.
- osErrorParameter: thread_id is NULL or invalid.
- osErrorResource: the thread is in an invalid state.
- osErrorISR: the function osThreadSuspend cannot be called from interrupt service routines.
- osErrorSafetyClass: the calling thread safety class is lower than the safety class of the specified thread.

Note
  This function cannot be called from Interrupt Service Routines.
  This function must not be called to suspend the running thread when the kernel is locked, i.e. osKernelLock.

## ◆ osThreadResume()

osStatus_t osThreadResume | ( | osThreadId_t | thread_id | ) |

Resume execution of a thread.

Parameters

  [in] | thread_id | thread ID obtained by osThreadNew or osThreadGetId.

Returns
  status code that indicates the execution status of the function.

The function osThreadResume puts the thread identified by parameter thread_id (which has to be in BLOCKED state) back to the READY state. If the resumed thread has a higher priority than the running thread a context switch occurs immediately.

The thread becomes ready regardless of the reason why the thread was blocked. Thus it is not recommended to resume a thread not suspended by osThreadSuspend.

Functions that will put a thread into BLOCKED state are: osEventFlagsWait and osThreadFlagsWait, osDelay and osDelayUntil, osMutexAcquire and osSemaphoreAcquire, osMessageQueueGet, osMemoryPoolAlloc, osThreadJoin, osThreadSuspend.

Possible osStatus_t return values:

- osOK: the thread has been resumed successfully.
- osErrorParameter: thread_id is NULL or invalid.
- osErrorResource: the thread is in an invalid state.
- osErrorISR: the function osThreadResume cannot be called from interrupt service routines.
- osErrorSafetyClass: the calling thread safety class is lower than the safety class of the specified thread.

Note
  This function cannot be called from Interrupt Service Routines.
  This function may be called when kernel is locked (osKernelLock). Under this circumstances a potential context switch is delayed until the kernel gets unlocked, i.e. osKernelUnlock or osKernelRestoreLock.

## ◆ osThreadDetach()

osStatus_t osThreadDetach | ( | osThreadId_t | thread_id | ) |

Detach a thread (thread storage can be reclaimed when thread terminates).

Parameters

  [in] | thread_id | thread ID obtained by osThreadNew or osThreadGetId.

Returns
  status code that indicates the execution status of the function.

The function osThreadDetach changes the attribute of a thread (specified by thread_id) to osThreadDetached. Detached threads are not joinable with osThreadJoin. When a detached thread is terminated, all resources are returned to the system. The behavior of osThreadDetach on an already detached thread is undefined.

Possible osStatus_t return values:

- osOK: the attribute of the specified thread has been changed to detached successfully.
- osErrorParameter: thread_id is NULL or invalid.
- osErrorResource: the thread is in an invalid state.
- osErrorISR: the function osThreadDetach cannot be called from interrupt service routines.
- osErrorSafetyClass: the calling thread safety class is lower than the safety class of the specified thread.

Note
  This function cannot be called from Interrupt Service Routines.

## ◆ osThreadJoin()

osStatus_t osThreadJoin | ( | osThreadId_t | thread_id | ) |

Wait for specified thread to terminate.

Parameters

  [in] | thread_id | thread ID obtained by osThreadNew or osThreadGetId.

Returns
  status code that indicates the execution status of the function.

The function osThreadJoin waits for the thread specified by thread_id to terminate. If that thread has already terminated, then osThreadJoin returns immediately. The thread must be joinable. By default threads are created with the attribute osThreadDetached.

Possible osStatus_t return values:

- osOK: if the thread has already been terminated and joined or once the thread has been terminated and the join operations succeeds.
- osErrorParameter: thread_id is NULL or invalid.
- osErrorResource: the thread is in an invalid state (ex: not joinable).
- osErrorISR: the function osThreadJoin cannot be called from interrupt service routines.
- osErrorSafetyClass: the calling thread safety class is lower than the safety class of the specified thread.

Note
  This function cannot be called from Interrupt Service Routines.
  Only one thread shall call osThreadJoin to join the target thread. If multiple threads try to join simultaneously with the same thread, the results are undefined.

## ◆ osThreadExit()

__NO_RETURN void osThreadExit | ( | void |  | ) |

Terminate execution of current running thread.

The function osThreadExit terminates the calling thread. This allows the thread to be synchronized with osThreadJoin.

Note
  This function cannot be called from Interrupt Service Routines.

Code Example

__NO_RETURN void worker (void *argument) {
// do something
osDelay(1000U);
osThreadExit();
}

## ◆ osThreadTerminate()

osStatus_t osThreadTerminate | ( | osThreadId_t | thread_id | ) |

Terminate execution of a thread.

Parameters

  [in] | thread_id | thread ID obtained by osThreadNew or osThreadGetId.

Returns
  status code that indicates the execution status of the function.

The function osThreadTerminate removes the thread specified by parameter thread_id from the list of active threads. If the thread is currently RUNNING, the thread terminates and the execution continues with the next READY thread. If no such thread exists, the function will not terminate the running thread, but return osErrorResource.

Possible osStatus_t return values:

- osOK: the specified thread has been removed from the active thread list successfully.
- osErrorParameter: thread_id is NULL or invalid.
- osErrorResource: the thread is in an invalid state or no other READY thread exists.
- osErrorISR: the function osThreadTerminate cannot be called from interrupt service routines.
- osErrorSafetyClass: the calling thread safety class is lower than the safety class of the specified thread.

Note
  This function cannot be called from Interrupt Service Routines.
  Avoid calling the function with a thread_id that does not exist or has been terminated already.
  osThreadTerminate destroys non-joinable threads and removes their thread_id from the system. Subsequent access to the thread_id (for example osThreadGetState) will return an osThreadError. Joinable threads will not be destroyed and return the status osThreadTerminated until they are joined with osThreadJoin.

Code Example

#include "cmsis_os2.h"
void Thread_1 (void *arg); // function prototype for Thread_1
void ThreadTerminate_example (void) {
osStatus_t status;
osThreadId_t id;
id = osThreadNew(Thread_1, NULL, NULL); // create the thread
// do something
status = osThreadTerminate(id); // stop the thread
if (status == osOK) {
// Thread was terminated successfully
}
else {
// Failed to terminate a thread
}
}

## ◆ osThreadGetStackSize()

uint32_t osThreadGetStackSize | ( | osThreadId_t | thread_id | ) |

Get stack size of a thread.

Parameters

  [in] | thread_id | thread ID obtained by osThreadNew or osThreadGetId.

Returns
  stack size in bytes.

The function osThreadGetStackSize returns the stack size of the thread specified by parameter thread_id. In case of an error, it returns 0.

Note
  This function cannot be called from Interrupt Service Routines.

## ◆ osThreadGetStackSpace()

uint32_t osThreadGetStackSpace | ( | osThreadId_t | thread_id | ) |

Get available stack space of a thread based on stack watermark recording during execution.

Parameters

  [in] | thread_id | thread ID obtained by osThreadNew or osThreadGetId.

Returns
  remaining stack space in bytes.

The function osThreadGetStackSpace returns the size of unused stack space for the thread specified by parameter thread_id. In case of an error, it returns 0.

Note
  This function cannot be called from Interrupt Service Routines.

## ◆ osThreadGetCount()

uint32_t osThreadGetCount | ( | void |  | ) |

Get number of active threads.

Returns
  number of active threads.

The function osThreadGetCount returns the number of active threads or 0 in case of an error.

Note
  This function cannot be called from Interrupt Service Routines.

## ◆ osThreadEnumerate()

uint32_t osThreadEnumerate | ( | osThreadId_t * | thread_array,
|  | uint32_t | array_items
| ) |  |

Enumerate active threads.

Parameters

  [out] | thread_array | pointer to array for retrieving thread IDs.
  [in] | array_items | maximum number of items in array for retrieving thread IDs.

Returns
  number of enumerated threads.

The function osThreadEnumerate returns the number of enumerated threads or 0 in case of an error.

Note
  This function cannot be called from Interrupt Service Routines.

## ◆ osThreadFeedWatchdog()

osStatus_t osThreadFeedWatchdog | ( | uint32_t | ticks | ) |

Feed watchdog of the current running thread.

Parameters

  [in] | ticks | interval in kernel ticks until the thread watchdog expires, or 0 to stop the watchdog

Returns
  status code that indicates the execution status of the function.

The function osThreadFeedWatchdog restarts watchdog of the current running thread. If the thread watchdog is not fed again within the ticks interval osWatchdogAlarm_Handler will be called.

Possible osStatus_t return values:

- osOK: the watchdog timer was restarted successfully.
- osError: cannot be executed (kernel not running).
- osErrorISR: the function osThreadFeedWatchdog cannot be called from interrupt service routines.

Note
  This function cannot be called from Interrupt Service Routines.

Code Example:

#include "cmsis_os2.h"
void Thread_1 (void const *arg) { // Thread function
osStatus_t status; // Status of the executed function
:
while (1) {
status = osThreadFeedWatchdog(500U); // Feed thread watchdog for 500 ticks
// verify status value here
:
}
}

## ◆ osThreadProtectPrivileged()

osStatus_t osThreadProtectPrivileged | ( | void |  | ) |

Protect creation of privileged threads.

Returns
  status code that indicates the execution status of the function.

The function osThreadProtectPrivileged disables creation of new privileged threads. After its successful execution, no new threads with privilege execution mode (osThreadPrivileged attribute) can be created. Kernel shall be in ready state or running when osThreadProtectPrivileged is called.

Possible osStatus_t return values:

- osOK: the creation of new privileged threads is disabled.
- osError: cannot be executed (kernel not ready).
- osErrorISR: the function osThreadProtectPrivileged cannot be called from interrupt service routines.

Note
  This function cannot be called from Interrupt Service Routines.

Code Example:

#include "cmsis_os2.h"
int main (void) {
osStatus_t status;
:
status = osKernelInitialize(); // Initialize CMSIS-RTOS2 kernel
// verify status value here.
: // Create privileged threads
status = osThreadProtectPrivileged(); // Disable creation of new privileged threads.
// verify status value here.
: // Start the kernel
}

## ◆ osThreadSuspendClass()

osStatus_t osThreadSuspendClass | ( | uint32_t | safety_class,
|  | uint32_t | mode
| ) |  |

Suspend execution of threads for specified safety classes.

Parameters

  [in] | safety_class | safety class.
  [in] | mode | safety mode.

Returns
  status code that indicates the execution status of the function.

The function osThreadSuspendClass suspends execution of threads based on safety class assignment. safety_class provides the reference safety class value, while mode is considered as a bitmap that additionally specifies the safety classes to be suspended.

If osSafetyWithSameClass is set in mode than the threads with safety class value equal to safety_class will be suspended.
If osSafetyWithLowerClass is set in mode than the threads with safety class value lower than safety_class will be suspended.

Possible osStatus_t return values:

- osOK: the threads with specified safety class have been suspended successfully.
- osErrorParameter: safety_class is invalid.
- osErrorResource: no other READY thread exists.
- osErrorISR: the function osThreadSuspendClass is called from interrupt other than osWatchdogAlarm_Handler.
- osErrorSafetyClass: the calling thread safety class is lower than the safety class specified by safety_class and mode.

Code Example:

#include "cmsis_os2.h"
void SuspendNonCriticalClasses (void) {
osStatus_t status;
status = osThreadSuspendClass(4U, osSafetyWithSameClass | osSafetyWithLowerClass); // Suspends threads with safety class 4 or lower
// verify status value here.
}

## ◆ osThreadResumeClass()

osStatus_t osThreadResumeClass | ( | uint32_t | safety_class,
|  | uint32_t | mode
| ) |  |

Resume execution of threads for specified safety classes.

Parameters

  [in] | safety_class | safety class.
  [in] | mode | safety mode.

Returns
  status code that indicates the execution status of the function.

The function osThreadResumeClass resumes execution of threads based on safety class assignment. safety_class provides the reference safety class value, while mode is considered as a bitmap that additionally specifies the safety classes to be resumed.

If osSafetyWithSameClass is set in mode than the threads with safety class value equal to safety_class will be resumed.
If osSafetyWithLowerClass is set in mode than the threads with safety class value lower than safety_class will be resumed.

Possible osStatus_t return values:

- osOK: the threads with specified safety class have been resumed successfully.
- osErrorParameter: safety_class is invalid.
- osErrorISR: the function osThreadResumeClass is called from interrupt other than osWatchdogAlarm_Handler.
- osErrorSafetyClass: the calling thread safety class is lower than the safety class specified by safety_class and mode.

Code Example:

#include "cmsis_os2.h"
void ResumeNonCriticalClasses (void) {
osStatus_t status;
status = osThreadResumeClass(4U, osSafetyWithSameClass | osSafetyWithLowerClass); // Resumes threads with safety class 4 or lower
// verify status value here.
}

## ◆ osThreadTerminateZone()

osStatus_t osThreadTerminateZone | ( | uint32_t | zone | ) |

Terminate execution of threads assigned to a specified MPU protected zone.

Parameters

  [in] | zone | MPU protected zone.

Returns
  status code that indicates the execution status of the function.

The function osThreadTerminateZone terminates execution of threads assigned to the MPU Protected Zone as given by zone parameter.

Possible osStatus_t return values:

- osOK: the threads within the specified MPU Protected Zone have been terminated successfully.
- osErrorParameter: zone is invalid.
- osErrorResource: no other READY thread exists.
- osErrorISR: the function osThreadTerminateZone is called from interrupt other than fault.
- osError: the function osThreadTerminateZone is called from thread.

Note
  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 osThreadGetState) will return an osThreadError. Joinable threads will not be destroyed and return the status osThreadTerminated until they are joined with osThreadJoin.

Code Example:

#include "cmsis_os2.h"
void TerminateFaultedThreads (void) { // to be called from an exception fault context
osStatus_t status;
status = osThreadTerminateZone(3U); // Terminates threads assigned to MPU Protected Zone 3
// verify status value here.
}

## ◆ osThreadSetAffinityMask()

osStatus_t osThreadSetAffinityMask | ( | osThreadId_t | thread_id,
|  | uint32_t | affinity_mask
| ) |  |

Set processor affinity mask of a thread.

Parameters

  [in] | thread_id | thread ID obtained by osThreadNew or osThreadGetId.
  [in] | affinity_mask | processor affinity mask for the thread.

Returns
  status code that indicates the execution status of the function.

The function osThreadSetAffinityMask sets the affinity mask of the thread specified by parameter thread_id to the mask specified by the parameter affinity_mask. The mask indicates on which processor(s) the thread should run (0 indicates on any processor).

Possible osStatus_t return values:

- osOK: the affinity mask of the specified thread has been set successfully.
- osErrorParameter: thread_id is NULL or invalid or affinity_mask is incorrect.
- osErrorResource: the thread is in an invalid state.
- osErrorISR: the function osThreadSetAffinityMask cannot be called from interrupt service routines.
- osErrorSafetyClass: the calling thread safety class is lower than the safety class of the specified thread.

Note
  This function cannot be called from Interrupt Service Routines.

Code Example

#include "cmsis_os2.h"
void Thread_1 (void const *arg) { // Thread function
osThreadId_t id; // id for the currently running thread
osStatus_t status; // status of the executed function
id = osThreadGetId(); // Obtain ID of current running thread
status = osThreadSetAffinityMask(id, osThreadProcessor(1)); // run thread processor #1
if (status == osOK) {
// Thread affinity mask set to processor number 1
}
else {
// Failed to set the affinity mask
}
}

## ◆ osThreadGetAffinityMask()

uint32_t osThreadGetAffinityMask | ( | osThreadId_t | thread_id | ) |

Get current processor affinity mask of a thread.

Parameters

  [in] | thread_id | thread ID obtained by osThreadNew or osThreadGetId.

Returns
  current processor affinity mask of the specified thread.

The function osThreadGetAffinityMask returns the affinity mask of the thread specified by parameter thread_id. In case of an error, it returns 0.

Note
  This function cannot be called from Interrupt Service Routines.

Code Example

#include "cmsis_os2.h"
void Thread_1 (void const *arg) { // Thread function
osThreadId_t id; // id for the currently running thread
uint32_t affinity_mask; // thread affinity mask
id = osThreadGetId(); // Obtain ID of current running thread
affinity_mask = osThreadGetAffinityMask(id); // Obtain the thread affinity mask
}

## ◆ osWatchdogAlarm_Handler()

uint32_t osWatchdogAlarm_Handler | ( | osThreadId_t | thread_id | ) |

Handler for expired thread watchdogs.

Parameters

  [in] | thread_id | thread ID obtained by osThreadNew or osThreadGetId.

Returns
  new watchdog reload value or 0 to stop the watchdog.

The callback function osWatchdogAlarm_Handler is called by the kernel when a thread watchdog expires. Parameter thread_id identifies the thread which has the expired thread watchdog. The function needs to be implemented in user application.

Return new reload value to restart the watchdog. Return 0 to stop the thread watchdog.

Note
  The callback function is called from interrupt.
  When multiple watchdogs expire in the same tick, this function is called for each thread with highest safety class first.

Code Example:

#include "cmsis_os2.h"
uint32_t osWatchdogAlarm_Handler (osThreadId_t thread_id) {
uint32_t safety_class;
uint32_t next_interval;
safety_class = osThreadGetClass(thread_id);
/* Handle the watchdog depending on how safety-critical is the thread */
if (safety_class < ...){
:
} else {
:
}
return next_interval;
}

## ◆ osZoneSetup_Callback()

void osZoneSetup_Callback | ( | uint32_t | zone | ) |

Setup MPU protected zone (called when zone changes).

Parameters

  [in] | zone | zone number.

The callback function osZoneSetup_Callback is called by the kernel when MPU Protected Zone changes. The function shall be implemented in user application.

Code Example:

/* Update MPU settings for newly activating Zone */
void osZoneSetup_Callback (uint32_t zone) {
if (zone >= ZONES_NUM) {
//Issue an error for incorrect zone value
}
ARM_MPU_Disable();
ARM_MPU_Load(mpu_table[zone], MPU_REGIONS);
ARM_MPU_Enable(MPU_CTRL_PRIVDEFENA_Msk);
}

`ZONES_NUM` is the total amount of zones allocated by the application. For `ARM_MPU_`... functions refer to MPU Functions in CMSIS-Core documentation.