/*=======0=========1=========2=========3=========4=========5=========6=========7=========8=========9=========0=========1====*/
//  ==== Thread Management ====
/** 
\addtogroup CMSIS_RTOS_ThreadMgmt Thread Management
\ingroup CMSIS_RTOS CMSIS_RTOSv2
\brief Define, create, and control thread functions.
\details 
The Thread Management function group allows defining, creating, and controlling thread functions in the system.

\note Thread management functions cannot be called from \ref CMSIS_RTOS_ISR_Calls "Interrupt Service Routines".

\anchor ThreadStates
Thread states
-------------
Threads can be in the following states:

 - \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
   state.
 - \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
   \ref ThreadStates "BLOCKED", the next \ref ThreadStates "READY" thread with the highest priority becomes the \ref ThreadStates "RUNNING" thread.
 - \b BLOCKED: Threads that are blocked either delayed, waiting for an event to occur or suspended are in the \ref ThreadStates "BLOCKED"
   state.
 - \b TERMINATED: When \ref osThreadTerminate is called, threads are \ref ThreadStates "TERMINATED" with resources not yet released (applies to \ref joinable_threads "joinable threads).
 - \b INACTIVE: Threads that are not created or have been terminated with all resources released are in the \ref ThreadStates "INACTIVE" state.
 
\image html "ThreadStatus.png" "Thread State and State Transitions"


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

\anchor threadConfig_procmode
Processor Mode for Thread Execution
-------------

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.
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.

\anchor thread_examples
Thread Examples
===============
The following examples show various scenarios to create threads:
 
<b>Example 1 - Create a simple thread</b> 

Create a thread out of the function thread1 using all default values for thread attributes and memory allocated by the system.
 
\code
__NO_RETURN void thread1 (void *argument) {
  // ...
  for (;;) {}
}
 
int main (void) {
  osKernelInitialize();
  ;
  osThreadNew(thread1, NULL, NULL);     // Create thread with default settings
  ;
  osKernelStart(); 
}
\endcode

<b>Example 2 - Create thread with stack non-default stack size</b>

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.

\code
__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
  ;
}
\endcode

<b>Example 3 - Create thread with statically allocated stack</b>
 
Similar to the simple thread all attributes are default. The stack is statically allocated using the \c uint64_t array
\c thread1_stk_1. This allocates 64*8 Bytes (=512 Bytes) with an alignment of 8 Bytes (mandatory for Cortex-M stack memory). 
 
\ref osThreadAttr_t.stack_mem holds a pointer to the stacks lowest address. 
 
\ref osThreadAttr_t.stack_size is used to pass the stack size in Bytes to \ref osThreadNew.

\code
__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
  ;
}
\endcode

<b>Example 4 - Thread with statically allocated task control block</b>
 
Typically this method is chosen together with a statically allocated stack as shown in Example 2. 
\code 
#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
  ;
}
\endcode

<b>Example 5 - Create thread with a different priority</b> 
 
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.

\code
__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);
  ;
}
\endcode

\anchor joinable_threads
<b>Example 6 - Joinable threads</b>
 
In this example a master thread creates four threads with the \ref osThreadJoinable attribute. These will do some work and
return using the \ref osThreadExit call after finished. \ref osThreadJoin is used to synchronize the thread termination. 


\code 
__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(); 
}
\endcode
   
@{
*/
/*=======0=========1=========2=========3=========4=========5=========6=========7=========8=========9=========0=========1====*/
/**
\typedef osThreadState_t
\details
State of a thread as retrieved by \ref osThreadGetState. In case \b osThreadGetState fails or if it is called from an ISR, it
will return \c osThreadError, otherwise it returns the thread state.

\var osThreadState_t::osThreadInactive
\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)

\var osThreadState_t::osThreadReady
\details The thread is ready for execution but not currently running.

\var osThreadState_t::osThreadRunning
\details The thread is currently running.

\var osThreadState_t::osThreadBlocked
\details The thread is currently blocked (delayed, waiting for an event or suspended).

\var osThreadState_t::osThreadTerminated
\details The thread is terminated and all its resources are not yet freed (applies to \ref joinable_threads "joinable threads).

\var osThreadState_t::osThreadError
\details The thread does not exist (has raised an error condition) and cannot be scheduled.
*/

/*=======0=========1=========2=========3=========4=========5=========6=========7=========8=========9=========0=========1====*/
/**
\typedef osPriority_t
\details

The \b osPriority_t value specifies the priority for a thread. The default thread priority should be \a 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 <b>priority inheritance</b>
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.

\var osPriority_t::osPriorityIdle
\details This lowest priority should not be used for any other thread. 

\var osPriority_t::osPriorityISR 
\details This highest priority might be used by the RTOS implementation but must not be used for any user thread.
*/

/*=======0=========1=========2=========3=========4=========5=========6=========7=========8=========9=========0=========1====*/
/**
\typedef void (*osThreadFunc_t) (void *argument)
\details Entry function for threads. Setting up a new thread (\ref 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.

\param[in] argument arbitrary user data set on \ref osThreadNew.
*/

/*=======0=========1=========2=========3=========4=========5=========6=========7=========8=========9=========0=========1====*/
/**
\typedef osThreadId_t
\details Returned by:
- \ref osThreadNew
- \ref osThreadGetId
- \ref osThreadEnumerate
- \ref osMutexGetOwner
*/

/*=======0=========1=========2=========3=========4=========5=========6=========7=========8=========9=========0=========1====*/
/**
\struct osThreadAttr_t
\details Specifies the following attributes for the \ref osThreadNew function.
*/
/*=======0=========1=========2=========3=========4=========5=========6=========7=========8=========9=========0=========1====*/

/**
\def osErrorId
\details Error return code from \ref osThreadGetClass and \ref osThreadGetZone.
*/
/*=======0=========1=========2=========3=========4=========5=========6=========7=========8=========9=========0=========1====*/

/**
\def osThreadJoinable
\details
Bitmask for a thread that can be joined.
Intended for use in \e attr_bits of \ref osThreadAttr_t type argument for \ref osThreadNew function.

A thread in this state can be joined using \ref osThreadJoin.
*/
/*=======0=========1=========2=========3=========4=========5=========6=========7=========8=========9=========0=========1====*/

/**
\def osThreadDetached
\details
Bitmask for a thread that cannot be joined.
Intended for use in \e attr_bits of \ref osThreadAttr_t type argument for \ref osThreadNew function.

A thread in this state cannot be joined using \ref osThreadJoin.
*/

/*=======0=========1=========2=========3=========4=========5=========6=========7=========8=========9=========0=========1====*/
/**
\def osThreadUnprivileged
\details
Bitmask for a thread that runs in unprivileged mode.
Intended for use in \e attr_bits of \ref osThreadAttr_t type argument for \ref osThreadNew function.

In \b 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.
*/

/**
\def osThreadPrivileged
\details
Bitmask for a thread that runs in privileged mode.
Intended for use in \e attr_bits of \ref osThreadAttr_t type argument for \ref osThreadNew function.

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

/*=======0=========1=========2=========3=========4=========5=========6=========7=========8=========9=========0=========1====*/
/**
\def osThreadZone(n)
\param  n MPU Protected Zone value.
\details

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

<b>Code Example:</b>
\code
/* 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
};
\endcode
*/

/*=======0=========1=========2=========3=========4=========5=========6=========7=========8=========9=========0=========1====*/
/**
\def osThreadProcessor(n)
\param  n processor number, starting with n=0 for processor #0. The number of supported processors depend on the hardware.
\details

The preprocessor macro \b osThreadProcessor constructs the value for the osThreadAttr_t::affinity_mask derived from \a n.
*/


/*=======0=========1=========2=========3=========4=========5=========6=========7=========8=========9=========0=========1====*/
/**
\fn osThreadId_t osThreadNew (osThreadFunc_t func, void *argument, const osThreadAttr_t *attr)
\details
The function \b osThreadNew starts a thread function by adding it to the list of active threads and sets it to state
\ref ThreadStates "READY". Arguments for the thread function are passed using the parameter pointer \a *argument. When the priority of the
created thread function is higher than the current \ref ThreadStates "RUNNING" thread, the created thread function starts instantly and
becomes the new \ref ThreadStates "RUNNING" thread. Thread attributes are defined with the parameter pointer \a 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 \ref osKernelStart), but not before it is initialized (call to \ref osKernelInitialize).

The function \b osThreadNew returns the pointer to the thread object identifier or \token{NULL} in case of an error.

\note Cannot be called from \ref CMSIS_RTOS_ISR_Calls "Interrupt Service Routines".

\b Code \b Example

Refer to the \ref thread_examples "Thread Examples" section.
*/

/*=======0=========1=========2=========3=========4=========5=========6=========7=========8=========9=========0=========1====*/
/**
\fn const char *osThreadGetName (osThreadId_t thread_id)
\details
The function \b osThreadGetName returns the pointer to the name string of the thread identified by parameter \a thread_id or
\token{NULL} in case of an error.

\note This function may be called from \ref CMSIS_RTOS_ISR_Calls "Interrupt Service Routines".

<b>Code Example</b>
\code
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
  }
}
\endcode
*/

/*=======0=========1=========2=========3=========4=========5=========6=========7=========8=========9=========0=========1====*/
/**
\fn uint32_t osThreadGetClass (osThreadId_t thread_id);
\details
The function \b osThreadGetClass returns safety class assigned to the thread identified by parameter \a thread_id. In case of an
error, it returns \ref osErrorId.
*/

/*=======0=========1=========2=========3=========4=========5=========6=========7=========8=========9=========0=========1====*/
/**
\fn uint32_t osThreadGetZone (osThreadId_t thread_id);
\details
The function \b osThreadGetZone returns the MPU Protected Zone value assigned to the thread identified by parameter \a thread_id.
In case of an error, it returns \ref osErrorId.
*/

/*=======0=========1=========2=========3=========4=========5=========6=========7=========8=========9=========0=========1====*/
/**
\fn osThreadId_t osThreadGetId (void)
\details
The function \b 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 \ref CMSIS_RTOS_ISR_Calls "Interrupt Service Routines".

<b>Code Example</b>
\code
void ThreadGetId_example (void) {
  osThreadId_t id;                              // id for the currently running thread
   
  id = osThreadGetId();
  if (id == NULL) {
    // Failed to get the id
  }
}
\endcode
*/
/*=======0=========1=========2=========3=========4=========5=========6=========7=========8=========9=========0=========1====*/
/**
\fn osThreadState_t osThreadGetState (osThreadId_t thread_id)
\details
The function \b osThreadGetState returns the state of the thread identified by parameter \a thread_id. In case it fails or
if it is called from an ISR, it will return \c osThreadError, otherwise it returns the thread state (refer to
\ref osThreadState_t for the list of thread states).
 
\note This function \b cannot be called from \ref CMSIS_RTOS_ISR_Calls "Interrupt Service Routines".
*/

/*=======0=========1=========2=========3=========4=========5=========6=========7=========8=========9=========0=========1====*/
/**
\fn osStatus_t osThreadSetPriority (osThreadId_t thread_id, osPriority_t priority)
\details
The function \b osThreadSetPriority changes the priority of an active thread specified by the parameter \a thread_id to the
priority specified by the parameter \a priority. 

Possible \ref osStatus_t return values:
    - \em osOK: the priority of the specified thread has been changed successfully.
    - \em osErrorParameter: \a thread_id is \token{NULL} or invalid or \a priority is incorrect.
    - \em osErrorResource: the thread is in an invalid state.
    - \em osErrorISR: the function \b osThreadSetPriority cannot be called from interrupt service routines.
    - \em osErrorSafetyClass: the calling thread safety class is lower than the safety class of the specified thread.

\note This function \b cannot be called from \ref CMSIS_RTOS_ISR_Calls "Interrupt Service Routines".

<b>Code Example</b>
\code
#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
  }
  :
}
\endcode
*/
/*=======0=========1=========2=========3=========4=========5=========6=========7=========8=========9=========0=========1====*/
/**
\fn osPriority_t osThreadGetPriority (osThreadId_t thread_id)
\details
The function \b osThreadGetPriority returns the priority of an active thread specified by the parameter \a thread_id.

Possible \ref osPriority_t return values:
    - \em priority: the priority of the specified thread.
    - \em osPriorityError: priority cannot be determined or is illegal. It is also returned when the function is called from
      \ref CMSIS_RTOS_ISR_Calls "Interrupt Service Routines".

\note This function \b cannot be called from \ref CMSIS_RTOS_ISR_Calls "Interrupt Service Routines".

<b>Code Example</b>
\code
#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
}
\endcode
*/
/*=======0=========1=========2=========3=========4=========5=========6=========7=========8=========9=========0=========1====*/
/**
\fn osStatus_t osThreadYield (void)
\details
The function \b osThreadYield passes control to the next thread with the same priority that is in the \ref ThreadStates "READY" state. 
If there is no other thread with the same priority in state \ref ThreadStates "READY", then the current thread continues execution and
no thread switch occurs. \b osThreadYield does not set the thread to state \ref ThreadStates "BLOCKED". Thus no thread with a lower
priority will be scheduled even if threads in state \ref ThreadStates "READY" are available.

Possible \ref osStatus_t return values:
    - \em osOK: control has been passed to the next thread successfully.
    - \em osError: an unspecified error has occurred.
    - \em osErrorISR: the function \b osThreadYield cannot be called from interrupt service routines.

\note This function \b cannot be called from \ref CMSIS_RTOS_ISR_Calls "Interrupt Service Routines".
\note This function <b>has no impact</b> when called when the kernel is locked, see \ref osKernelLock.

<b>Code Example</b>
\code
#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
    }
  }
}
\endcode
*/
/*=======0=========1=========2=========3=========4=========5=========6=========7=========8=========9=========0=========1====*/
/**
\fn osStatus_t osThreadSuspend (osThreadId_t thread_id)
\details
The function \b osThreadSuspend suspends the execution of the thread identified by parameter \em thread_id. The thread is put
into the \ref ThreadStates "BLOCKED" state (\ref osThreadBlocked). Suspending the running thread will cause a context switch to another
thread in \ref ThreadStates "READY" state immediately. The suspended thread is not executed until explicitly resumed with the function \ref osThreadResume. 

Threads that are already \ref ThreadStates "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 \ref osStatus_t return values:
    - \em osOK: the thread has been suspended successfully.
    - \em osErrorParameter: \a thread_id is \token{NULL} or invalid.
    - \em osErrorResource: the thread is in an invalid state.
    - \em osErrorISR: the function \b osThreadSuspend cannot be called from interrupt service routines.
    - \em osErrorSafetyClass: the calling thread safety class is lower than the safety class of the specified thread.

\note This function \b cannot be called from \ref CMSIS_RTOS_ISR_Calls "Interrupt Service Routines".
\note This function <b>must not</b> be called to suspend the running thread when the kernel is locked, i.e. \ref osKernelLock.

*/

/*=======0=========1=========2=========3=========4=========5=========6=========7=========8=========9=========0=========1====*/
/**
\fn osStatus_t osThreadResume (osThreadId_t thread_id)
\details
The function \b osThreadResume puts the thread identified by parameter \em thread_id (which has to be in \ref ThreadStates "BLOCKED" state)
back to the \ref ThreadStates "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 \ref osThreadSuspend.

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

Possible \ref osStatus_t return values:
    - \em osOK: the thread has been resumed successfully.
    - \em osErrorParameter: \a thread_id is \token{NULL} or invalid.
    - \em osErrorResource: the thread is in an invalid state.
    - \em osErrorISR: the function \b osThreadResume cannot be called from interrupt service routines.
    - \em osErrorSafetyClass: the calling thread safety class is lower than the safety class of the specified thread.

\note This function \b cannot be called from \ref CMSIS_RTOS_ISR_Calls "Interrupt Service Routines".
\note This function <b>may be</b> called when kernel is locked (\ref osKernelLock). Under this circumstances
	a potential context switch is delayed until the kernel gets unlocked, i.e. \ref osKernelUnlock or \ref osKernelRestoreLock.

*/

/*=======0=========1=========2=========3=========4=========5=========6=========7=========8=========9=========0=========1====*/
/**
\fn osStatus_t osThreadDetach (osThreadId_t thread_id)
\details
The function \b osThreadDetach changes the attribute of a thread (specified by \em thread_id) to \ref osThreadDetached.
Detached threads are not joinable with \ref osThreadJoin. When a detached thread is terminated, all resources are returned to
the system. The behavior of \ref osThreadDetach on an already detached thread is undefined.

Possible \ref osStatus_t return values:
    - \em osOK: the attribute of the specified thread has been changed to detached successfully.
    - \em osErrorParameter: \a thread_id is \token{NULL} or invalid.
    - \em osErrorResource: the thread is in an invalid state.
    - \em osErrorISR: the function \b osThreadDetach cannot be called from interrupt service routines.
    - \em osErrorSafetyClass: the calling thread safety class is lower than the safety class of the specified thread.

\note This function \b cannot be called from \ref CMSIS_RTOS_ISR_Calls "Interrupt Service Routines".
*/

/*=======0=========1=========2=========3=========4=========5=========6=========7=========8=========9=========0=========1====*/
/**
\fn osStatus_t osThreadJoin (osThreadId_t thread_id)
\details
The function \b osThreadJoin waits for the thread specified by \em thread_id to terminate. If that thread has already
terminated, then \ref osThreadJoin returns immediately. The thread must be joinable. By default threads are created with the
attribute \ref osThreadDetached.

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

\note This function \b cannot be called from \ref CMSIS_RTOS_ISR_Calls "Interrupt Service Routines". <br>
\note Only one thread shall call \b osThreadJoin to join the target thread. If multiple threads try to join simultaneously with the same thread,
       the results are undefined.

*/

/*=======0=========1=========2=========3=========4=========5=========6=========7=========8=========9=========0=========1====*/
/**
\fn __NO_RETURN void osThreadExit (void)
\details

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

\note This function \b cannot be called from \ref CMSIS_RTOS_ISR_Calls "Interrupt Service Routines".

\b Code \b Example
\code
__NO_RETURN void worker (void *argument) {
  // do something
  osDelay(1000U);
  osThreadExit();
}
\endcode
*/

/*=======0=========1=========2=========3=========4=========5=========6=========7=========8=========9=========0=========1====*/
/**
\fn osStatus_t osThreadTerminate (osThreadId_t thread_id)
\details
The function \b osThreadTerminate removes the thread specified by parameter \a thread_id from the list of active threads. If
the thread is currently \ref ThreadStates "RUNNING", the thread terminates and the execution continues with the next \ref ThreadStates "READY" thread. If no
such thread exists, the function will not terminate the running thread, but return \em osErrorResource.

Possible \ref osStatus_t return values:
    - \em osOK: the specified thread has been removed from the active thread list successfully.
    - \em osErrorParameter: \a thread_id is \token{NULL} or invalid.
    - \em osErrorResource: the thread is in an invalid state or no other \ref ThreadStates "READY" thread exists.
    - \em osErrorISR: the function \b osThreadTerminate cannot be called from interrupt service routines.
    - \em osErrorSafetyClass: the calling thread safety class is lower than the safety class of the specified thread.

\note This function \b cannot be called from \ref CMSIS_RTOS_ISR_Calls "Interrupt Service Routines".
\note Avoid calling the function with a \em thread_id that does not exist or has been terminated already.
\note \b osThreadTerminate destroys non-joinable threads and removes their thread_id from the system. Subsequent access to the
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.

<b>Code Example</b>
\code
#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
  }
}
\endcode
*/

/*=======0=========1=========2=========3=========4=========5=========6=========7=========8=========9=========0=========1====*/
/**
\fn uint32_t osThreadGetStackSize (osThreadId_t thread_id)
\details
The function \b osThreadGetStackSize returns the stack size of the thread specified by parameter \a thread_id. In case of an
error, it returns \token{0}.

\note This function \b cannot be called from \ref CMSIS_RTOS_ISR_Calls "Interrupt Service Routines".
*/

/*=======0=========1=========2=========3=========4=========5=========6=========7=========8=========9=========0=========1====*/
/**
\fn uint32_t osThreadGetStackSpace (osThreadId_t thread_id); 
\details
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}.

\note This function \b cannot be called from \ref CMSIS_RTOS_ISR_Calls "Interrupt Service Routines".
*/

/*=======0=========1=========2=========3=========4=========5=========6=========7=========8=========9=========0=========1====*/
/**
\fn uint32_t osThreadGetCount (void)
\details
The function \b osThreadGetCount returns the number of active threads or \token{0} in case of an error.

\note This function \b cannot be called from \ref CMSIS_RTOS_ISR_Calls "Interrupt Service Routines".
*/

/*=======0=========1=========2=========3=========4=========5=========6=========7=========8=========9=========0=========1====*/
/**
\fn uint32_t osThreadEnumerate (osThreadId_t *thread_array, uint32_t array_items)
\details
The function \b osThreadEnumerate returns the number of enumerated threads or \token{0} in case of an error.

\note This function \b cannot be called from \ref CMSIS_RTOS_ISR_Calls "Interrupt Service Routines".
*/

/*=======0=========1=========2=========3=========4=========5=========6=========7=========8=========9=========0=========1====*/
/**
\fn osStatus_t osThreadFeedWatchdog (uint32_t ticks);
\details
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.

Possible \ref osStatus_t return values:
    - \em osOK: the watchdog timer was restarted successfully.
    - \em osError: cannot be executed (kernel not running).
    - \em osErrorISR: the function \b osThreadFeedWatchdog cannot be called from interrupt service routines.

\note This function \b cannot be called from \ref CMSIS_RTOS_ISR_Calls "Interrupt Service Routines".

<b>Code Example:</b>
\code
#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
    :
  }
}
\endcode
*/

/*=======0=========1=========2=========3=========4=========5=========6=========7=========8=========9=========0=========1====*/
/**
\fn osStatus_t osThreadProtectPrivileged (void);
\details
The function \b osThreadProtectPrivileged disables creation of new privileged threads. After its successful execution, no new
threads with privilege execution mode (\ref osThreadPrivileged attribute) can be created.
Kernel shall be in ready state or running when \b osThreadProtectPrivileged is called.

Possible \ref osStatus_t return values:
    - \em osOK: the creation of new privileged threads is disabled.
    - \em osError: cannot be executed (kernel not ready).
    - \em osErrorISR: the function \b osThreadProtectPrivileged cannot be called from interrupt service routines.

\note This function \b cannot be called from \ref CMSIS_RTOS_ISR_Calls "Interrupt Service Routines".

<b>Code Example:</b>
\code
#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
}
\endcode
*/

/*=======0=========1=========2=========3=========4=========5=========6=========7=========8=========9=========0=========1====*/
/**
\fn osStatus_t osThreadSuspendClass (uint32_t safety_class, uint32_t mode);
\details
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.

If \ref osSafetyWithSameClass is set in \a mode than the threads with safety class value equal to \a safety_class will be suspended.
<br>
If \ref osSafetyWithLowerClass is set in \a mode than the threads with safety class value lower than \a safety_class will be suspended.

Possible \ref osStatus_t return values:
    - \em osOK: the threads with specified safety class have been suspended successfully.
    - \em osErrorParameter: \a safety_class is invalid.
    - \em osErrorResource: no other \ref ThreadStates "READY" thread exists.
    - \em osErrorISR: the function \b osThreadSuspendClass is called from interrupt other than \ref osWatchdogAlarm_Handler.
    - \em osErrorSafetyClass: the calling thread safety class is lower than the safety class specified by \a safety_class and \a mode.

<b>Code Example:</b>
\code
#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.
}
\endcode
*/

/*=======0=========1=========2=========3=========4=========5=========6=========7=========8=========9=========0=========1====*/
/**
\fn osStatus_t osThreadResumeClass (uint32_t safety_class, uint32_t mode);
\details
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.

If \ref osSafetyWithSameClass is set in \a mode than the threads with safety class value equal to \a safety_class will be resumed.
<br>
If \ref osSafetyWithLowerClass is set in \a mode than the threads with safety class value lower than \a safety_class will be resumed.


Possible \ref osStatus_t return values:
    - \em osOK: the threads with specified safety class have been resumed successfully.
    - \em osErrorParameter: \a safety_class is invalid.
    - \em osErrorISR: the function \b osThreadResumeClass is called from interrupt other than \ref osWatchdogAlarm_Handler.
    - \em osErrorSafetyClass: the calling thread safety class is lower than the safety class specified by \a safety_class and \a mode.

<b>Code Example:</b>
\code
#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.
}
\endcode
*/

/*=======0=========1=========2=========3=========4=========5=========6=========7=========8=========9=========0=========1====*/
/**
\fn osStatus_t osThreadTerminateZone (uint32_t zone);
\details
The function \b osThreadTerminateZone terminates execution of threads assigned to the MPU Protected Zone as given by \a zone parameter.

Possible \ref osStatus_t return values:
    - \em osOK: the threads within the specified MPU Protected Zone have been terminated successfully.
    - \em osErrorParameter: \a zone is invalid.
    - \em osErrorResource: no other \ref ThreadStates "READY" thread exists.
    - \em osErrorISR: the function \b osThreadTerminateZone is called from interrupt other than fault.
    - \em osError: the function \b osThreadTerminateZone is called from thread.

\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.

<b>Code Example:</b>
\code
#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.
}
\endcode
*/

/*=======0=========1=========2=========3=========4=========5=========6=========7=========8=========9=========0=========1====*/
/**
\fn osStatus_t osThreadSetAffinityMask (osThreadId_t thread_id, uint32_t affinity_mask);
\details
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. 
The mask indicates on which processor(s) the thread should run (\token{0} indicates on any processor).

Possible \ref osStatus_t return values:
    - \em osOK: the affinity mask of the specified thread has been set successfully.
    - \em osErrorParameter: \a thread_id is \token{NULL} or invalid or \a affinity_mask is incorrect.
    - \em osErrorResource: the thread is in an invalid state.
    - \em osErrorISR: the function \b osThreadSetAffinityMask cannot be called from interrupt service routines.
    - \em osErrorSafetyClass: the calling thread safety class is lower than the safety class of the specified thread.

\note This function \b cannot be called from \ref CMSIS_RTOS_ISR_Calls "Interrupt Service Routines".

<b>Code Example</b>
\code
#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
  }
}
\endcode
*/

/*=======0=========1=========2=========3=========4=========5=========6=========7=========8=========9=========0=========1====*/
/**
\fn uint32_t osThreadGetAffinityMask (osThreadId_t thread_id);
\details
The function \b osThreadGetAffinityMask returns the affinity mask of the thread specified by parameter \a thread_id. 
In case of an error, it returns \token{0}.

\note This function \b cannot be called from \ref CMSIS_RTOS_ISR_Calls "Interrupt Service Routines".

<b>Code Example</b>
\code
#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
}
\endcode
*/

/*=======0=========1=========2=========3=========4=========5=========6=========7=========8=========9=========0=========1====*/
/**
\fn uint32_t osWatchdogAlarm_Handler (osThreadId_t thread_id);
\details
The callback function \b osWatchdogAlarm_Handler is called by the kernel when a thread watchdog expires.
Parameter \a 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 \token{0} to stop the thread watchdog.

\note The callback function is called from interrupt.

\note
When multiple watchdogs expire in the same tick, this function is called for each thread with highest safety class first.

<b>Code Example:</b>
\code
#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;
}
\endcode
*/

/*=======0=========1=========2=========3=========4=========5=========6=========7=========8=========9=========0=========1====*/
/**
\fn void osZoneSetup_Callback (uint32_t zone);
\details
The callback function \b osZoneSetup_Callback is called by the kernel when MPU Protected Zone changes.
The function shall be implemented in user application.

<b>Code Example:</b>
\code
/* 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);
}
\endcode

\c ZONES_NUM is the total amount of zones allocated by the application.
For \c ARM_MPU_... functions refer to <a href="../Core/group__mpu__functions.html"><b>MPU Functions</b></a> in CMSIS-Core documentation.
*/

/// @}


// these struct members must stay outside the group to avoid double entries in documentation
/**

\var osThreadAttr_t::attr_bits
\details
The following bit masks can be used to set options:
 - \ref osThreadDetached : create thread in a detached mode (default).
 - \ref osThreadJoinable : create thread in \ref joinable_threads "joinable mode".  
 - \ref osThreadUnprivileged : create thread to execute in unprivileged mode.
 - \ref osThreadPrivileged : create thread to execute in privileged mode.  
 - \ref osThreadZone (m) : create thread assigned to MPU zone \token{m}.
 - \ref osSafetyClass (n) : create thread with safety class \token{n} assigned to it.

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.

\var osThreadAttr_t::cb_mem
\details
Pointer to a memory for the thread control block object. Refer to \ref CMSIS_RTOS_MemoryMgmt_Manual for more information.

Default: \token{NULL} to use \ref CMSIS_RTOS_MemoryMgmt_Automatic for the thread control block.

\var osThreadAttr_t::cb_size
\details
The size (in bytes) of memory block passed with \ref cb_mem. Required value depends on the underlying kernel implementation.

Default: \token{0} as the default is no memory provided with \ref cb_mem.

\var osThreadAttr_t::name
\details
Pointer to a constant string with a human readable name (displayed during debugging) of the thread object.

Default: \token{NULL} no name specified (debugger may display function name instead).

\var osThreadAttr_t::priority
\details
Specifies the initial thread priority with a value from #osPriority_t.

Default: \token{osPriorityNormal}.

\var osThreadAttr_t::stack_mem
\details
Pointer to a memory location for the thread stack (64-bit aligned). 

Default: \token{NULL} - the memory for the stack is provided by the system based on the configuration of underlying RTOS kernel .

\var osThreadAttr_t::stack_size
\details
The size (in bytes) of the stack specified by \ref stack_mem.

Default: \token{0} as the default is no memory provided with \ref stack_mem.

\var osThreadAttr_t::tz_module
\details
\if (ARMv8M)
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 <a href="../Core/group__context__trustzone__functions.html">TrustZone RTOS Context Management</a>.

Default: \token{0} not thread context specified.
\else
Applicable only for devices on Armv8-M architecture. Ignored on others.
\endif

\var osThreadAttr_t::affinity_mask
\details
Use the \ref osThreadProcessor macro to create the mask value. Multiple processors can be specified by OR-ing values.

Default: value \token{0} is RTOS implementation specific and may map to running on processor #0 or on any processor.
*/
