]> begriffs open source - cmsis/blob - CMSIS/DoxyGen/RTOS2/src/cmsis_os2_Tutorial.txt
RTX5: typo correction in documentation (rtx_evr.h)
[cmsis] / CMSIS / DoxyGen / RTOS2 / src / cmsis_os2_Tutorial.txt
1 /*=======0=========1=========2=========3=========4=========5=========6=========7=========8=========9=========0=========1====*/
2 /**
3 \page rtos2_tutorial Tutorial
4
5 This tutorial is an introduction to using a small footprint real-time operating system on an Arm Cortex-M microcontroller.
6 If you are used to writing procedural-based 'C' code on small 8-/16-bit microcontrollers, you may be doubtful about the need
7 for such an operating system. If you are not familiar with using an RTOS in real-time embedded systems, you should read this
8 chapter before dismissing the idea. The use of an RTOS represents a more sophisticated design approach, inherently fostering
9 structured code development which is enforced by the RTOS application programming interface (API). 
10
11 The RTOS structure allows you to take a more object-orientated design approach, while still programming in 'C'. The RTOS
12 also provides you with multithreaded support on a small microcontroller. These two features actually create quite a shift in
13 design philosophy, moving us away from thinking about procedural ‘C’ code and flow charts. Instead we consider the
14 fundamental program threads and the flow of data between them. The use of an RTOS also has several additional benefits which
15 may not be immediately obvious. Since an RTOS based project is composed of well-defined threads, it helps to improve project
16 management, code reuse, and software testing.
17
18 The tradeoff for this is that an RTOS has additional memory requirements and increased interrupt latency. Typically, the
19 Keil RTX5 RTOS will require 500 bytes of RAM and 5k bytes of code, but remember that some of the RTOS code would be
20 replicated in your program anyway. We now have a generation of small low-cost microcontrollers that have enough on-chip
21 memory and processing power to support the use of an RTOS. Developing using this approach is therefore much more accessible.
22
23 We will first look at setting up an introductory RTOS project for a Cortex-M based microcontroller. Next, we
24 will go through each of the RTOS primitives and how they influence the design of our application code. Finally, when we have
25 a clear understanding of the RTOS features, we will take a closer look at the RTOS configuration options. If you are used to
26 programming a microcontroller without using an RTOS i.e. bare metal, there are two key things to understand as you work
27 through this tutorial. In the first section, we will focus on creating and managing Threads. The key concept here is to
28 consider them running as parallel concurrent objects. In the second section, we will look at how to communicate between
29 threads. In this section the key concept is synchronization of the concurrent threads.
30
31
32 \section rtos2_tutorial_pre Prerequisites
33
34 It is assumed that you have Keil MDK installed on your PC. For download and installation instructions, please visit
35 the <a href="https://www2.keil.com/mdk5/install/" target="_blank">Getting Started</a> page. Once you have set up the tool,
36 open <a href="https://www2.keil.com/mdk5/packinstaller" target="_blank">Pack Installer</a>:
37 - Use the <b>Search</b> box on the <b>Devices</b> tab to look for the <b>STM32F103</b> device.
38 - On the <b>Packs</b> tab, download and install the <b>Keil:STM32F1xx_DFP</b> and the <b>Hitex:CMSIS_RTOS_Turorial</b> pack.
39
40 \note It is assumed that you are familiar with Arm Keil MDK and have basic 'C' programming knowledge.
41
42
43 \section rtos2_tutorial_first_steps First Steps with Keil RTX5
44
45 The RTOS itself consists of a scheduler which supports round-robin, pre-emptive and co-operative multitasking of program
46 threads, as well as time and memory management services. Inter-thread communication is supported by additional RTOS objects,
47 including signal thread and event flags, semaphores, mutex, message passing and a memory pool system. As we will see,
48 interrupt handling can also be accomplished by prioritized threads which are scheduled by the RTOS kernel.
49
50 \image html rtos_components.png
51
52
53 \section rtos2_tutorial_access Accessing the CMSIS-RTOS2 API
54
55 To access any of the CMSIS-RTOS2 features in our application code, it is necessary to include the following header file.
56 \code
57 #include <cmsis_os2.h>
58 \endcode
59 This header file is maintained by Arm as part of the CMSIS-RTOS2 standard. For Keil RTX5, this is the default API. Other
60 RTOS will have their own proprietary API but may provide a wrapper layer to implement the CMSIS-RTOS2 API so they can be
61 used where compatibility with the CMSIS standard is required.
62
63
64 \section rtos2_tutorial_threads Threads
65
66 The building blocks of a typical 'C' program are functions which we call to perform a specific procedure and which then
67 return to the calling function. In CMSIS-RTOS2, the basic unit of execution is a "Thread". A Thread is very similar to a 'C'
68 procedure but has some very fundamental differences.
69 \code
70 unsigned int procedure (void) {
71   ...
72         return(ch);                     
73 }
74  
75 void thread (void) {
76   while(1) {
77     ...
78         }
79 }       
80  
81 __NO_RETURN void Thread1(void*argument) {
82   while(1) {
83     ...
84   }
85 }
86 \endcode
87 While we always return from our 'C' function, once started an RTOS thread must contain a loop so that it never terminates
88 and thus runs forever. You can think of a thread as a mini self-contained program that runs within the RTOS. With the Arm
89 Compiler, it is possible to optimize a thread by using a \c __NO_RETURN macro. This attribute reduces the cost of calling a
90 function that never returns.
91
92 An RTOS program is made up of a number of threads, which are controlled by the RTOS scheduler. This scheduler uses the
93 SysTick timer to generate a periodic interrupt as a time base. The scheduler will allot a certain amount of execution time
94 to each thread. So \c thread1 will run for 5 ms then be de-scheduled to allow \c thread2 to run for a similar period;
95 \c thread2 will give way to \c thread3 and finally control passes back to \c thread1. By allocating these slices of runtime
96 to each thread in a round-robin fashion, we get the appearance of all three threads running in parallel to each other. 
97
98 Conceptually we can think of each thread as performing a specific functional unit of our program with all threads running
99 simultaneously. This leads us to a more object-orientated design, where each functional block can be coded and tested in
100 isolation and then integrated into a fully running program. This not only imposes a structure on the design of our final
101 application but also aids debugging, as a particular bug can be easily isolated to a specific thread. It also aids code
102 reuse in later projects. When a thread is created, it is also allocated its own thread ID. This is a variable which acts as
103 a handle for each thread and is used when we want to manage the activity of the thread.
104 \code
105 osThreadId_t id1, id2, id3;
106 \endcode
107 In order to make the thread-switching process happen, we have the code overhead of the RTOS and we have to dedicate a CPU
108 hardware timer to provide the RTOS time reference. In addition, each time we switch running threads, we have to save the
109 state of all the thread variables to a thread stack. Also, all the runtime information about a thread is stored in a thread
110 control block, which is managed by the RTOS kernel. Thus the “context switch time”, that is, the time to save the current
111 thread state and load up and start the next thread, is a crucial figure and will depend on both the RTOS kernel and the
112 design of the underlying hardware.
113
114 The Thread Control Block contains information about the status of a thread. Part of this information is its run state. In a
115 given system, only one thread can be running and all the others will be suspended but ready to run. The RTOS has various
116 methods of inter-thread communication (signals, semaphores, messages). Here, a thread may be suspended to wait to be
117 signaled by another thread or interrupt before it resumes its ready state, whereupon it can be placed into running state by
118 the RTOS scheduler.
119
120 | State   | Description |
121 |---------|-------------|
122 | Running | The currently running thread |
123 | Ready   | Threads ready to run |
124 | Wait    | Blocked threads waiting for an OS event |
125
126 At any given moment a single thread may be running. The remaining threads will be ready to run and will be scheduled by the
127 kernel. Threads may also be waiting pending an OS event. When this occurs they will return to the ready state and be
128 scheduled by the kernel.
129
130
131 \section rtos2_tutorial_start Starting the RTOS
132
133 To build a simple RTOS, program we declare each thread as a standard 'C' function and also declare a thread ID variable for
134 each function.
135 \code
136 void thread1 (void);    
137 void thread2 (void);
138  
139 osThreadId thrdID1, thrdID2;
140 \endcode
141 Once the processor leaves the reset vector, we will enter the \c main() function as normal. Once in \c main(), we must call
142 \ref osKernelInitialize() to setup the RTOS. It is not possible to call any RTOS function before the
143 \ref osKernelInitialize() function has successfully completed. Once \ref osKernelInitialize() has completed, we can create
144 further threads and other RTOS objects. This can be done by creating a launcher thread, in the example below this is called
145 \c app_main(). Inside the \c app_main() thread, we create all the RTOS threads and objects we need to start our application
146 running. As we will see later, it is also possible to dynamically create and destroy RTOS objects as the application is
147 running. Next, we can call \ref osKernelStart() to start the RTOS and the scheduler task switching. You can run any
148 initializing code you want before starting the RTOS to setup peripherals and initialize the hardware.
149 \code
150 void app_main(void *argument) {
151   T_led_ID1 = osThreadNew(led_Thread1, NULL, &ThreadAttr_LED1);
152   T_led_ID2 = osThreadNew(led_Thread2, NULL, &ThreadAttr_LED2);
153   osDelay(osWaitForever);
154   while (1)
155     ;
156 }
157  
158 void main(void) {
159   IODIR1 = 0x00FF0000;               // Do any C code you want
160   osKernelInitialize();              // Initialize the kernel
161   osThreadNew(app_main, NULL, NULL); // Create the app_main() launcher thread
162   osKernelStart();                   // Start the RTOS
163 }
164 \endcode
165 When threads are created they are also assigned a priority. If there are a number of threads ready to run and they all have
166 the same priority, they will be allotted run time in a round-robin fashion. However, if a thread with a higher priority
167 becomes ready to run, the RTOS scheduler will de-schedule the currently running thread and start the high priority thread
168 running. This is called pre-emptive priority-based scheduling. When assigning priorities, you have to be careful because the
169 high priority thread will continue to run until it enters a waiting state or until a thread of equal or higher priority is
170 ready to run.
171
172 \subsection rtos2_tutorial_ex1 Exercise 1 - A First CMSIS-RTOS2 Project
173
174 Open <a href="https://www2.keil.com/mdk5/packinstaller" target="_blank">Pack Installer</a>:
175 - Use the <b>Search</b> box on the <b>Boards</b> tab to look for the <b>CMSIS_RTOS_Tutorial</b> "board".
176 - On the <b>Examples</b> tab, copy <b>Ex 1 First Project</b> to your PC and start Keil MDK.
177
178
179 \section rtos2_tutorial_thread_create Creating Threads
180
181 Once the RTOS is running, there are a number of system calls that are used to manage and control the active threads. The
182 documentation lists \ref CMSIS_RTOS_ThreadMgmt "all thread management functions".
183
184 As we saw in the first example, the \c app_main() thread is used as a launcher thread to create the application threads.
185 This is done in two stages. First a thread structure is defined; this allows us to define the thread operating parameters.
186 \code
187 osThreadId thread1_id; // thread handle
188  
189 static const osThreadAttr_t threadAttr_thread1 = {
190         “Name_String ",            //Human readable Name for debugger
191     Attribute_bits Control_Block_Memory,
192     Control_Block_Size,
193     Stack_Memory,
194     Stack_Size,
195     Priority,
196     TrustZone_ID,
197     reserved};
198 \endcode
199 The thread structure requires us to define the name of the thread function, its thread priority, any special attribute bits,
200 its TrustZone_ID and its memory allocation. This is quite a lot of detail to go through but we will cover everything by the
201 end of this application note. Once the thread structure has been defined, the thread can be created using the
202 \ref osThreadNew() API call. Then the thread is created from within the application code, this is often the within the
203 \c app_main() thread but a thread can be created at any point within any thread.
204 \code
205 thread1_id = osThreadNew(name_Of_C_Function, argument,&threadAttr_thread1);
206 \endcode
207 This creates the thread and starts it running. It is also possible to pass a parameter to the thread when it starts.
208 \code
209 uint32_t startupParameter = 0x23;
210 thread1_id = osThreadNew(name_Of_C_Function, (uint32_t)startupParameter,&threadAttr_thread1);
211 \endcode
212
213
214 \subsection rtos2_tutorial_ex2 Exercise 2 - Creating and Managing Threads 
215
216
217 \section rtos2_tutorial_thread_mgmt Thread Management and Priority
218
219 When a thread is created it is assigned a priority level. The RTOS scheduler uses a thread’s priority to decide which thread
220 should be scheduled to run. If a number of threads are ready to run, the thread with the highest priority will be placed in
221 the run state. If a high priority thread becomes ready to run it will preempt a running thread of lower priority.
222 Importantly, a high priority thread running on the CPU will not stop running unless it blocks on an RTOS API call or is
223 preempted by a higher priority thread. A thread's priority is defined in the thread structure and the following priority
224 definitions are available. The default priority is \ref osPriorityNormal. The \ref osPriority_t value specifies the priority
225 for a thread.
226
227 Once the threads are running, there are a small number of RTOS system calls which are used to manage the running threads. It
228 is also then possible to elevate or lower a thread’s priority either from another function or from within its own code.
229 \code
230 osStatus   osThreadSetPriority(threadID, priority);
231 osPriority osThreadGetPriority(threadID);
232 \endcode
233 As well as creating threads, it is also possible for a thread to delete another active thread from the RTOS. Again, we use
234 the thread ID rather than the function name of the thread.
235 \code
236 osStatus = osThreadTerminate (threadID1);
237 \endcode                
238 If a thread wants to terminate itself then there is a dedicated exit function.
239 \code
240 osThreadExit (void)
241 \endcode
242 Finally, there is a special case of thread switching where the running thread passes control to the next ready thread of the
243 same priority. This is used to implement a third form of scheduling called co-operative thread switching.
244 \code
245 osStatus osThreadYield();               //switch to next ready to run thread at the same priority
246 \endcode
247
248
249 \subsection rtos2_tutorial_ex2_cont Exercise 2 continued - Creating and Managing Threads
250
251
252 \section rtos2_tutorial_ex2_mem_mgmt Memory Management
253
254 When each thread is created, it is assigned its own stack for storing data during the context switch. This should not be
255 confused with the native Cortex-M processor stack; it is really a block of memory that is allocated to the thread. A
256 default stack size is defined in the RTOS configuration file (we will see this later) and this amount of memory will be
257 allocated to each thread unless we override it to allocate a custom size. The default stack size will be assigned to a
258 thread if the stack size value in the thread definition structure is set to zero. If necessary a thread can be given
259 additional memory resources by defining a bigger stack size in the thread structure. Keil RTX5 supports several memory
260 models to assign this thread memory. The default model is a global memory pool. In this model each RTOS object that is
261 created (threads, message queues, semaphores etc.) are allocated memory from a single block of memory.
262  
263 If an object is destroyed the memory it has been assigned is returned to the memory pool. This has the advantage of memory
264 reuse but also introduces the possible problem of memory fragmentation.
265
266 The size of the global memory pool is defined in the configuration file:
267 \code
268 #define OS_DYNAMIC_MEM_SIZE         4096
269 \endcode        
270 And the default stack size for each thread is defined in the threads section:
271 \code
272 #define OS_STACK_SIZE               256
273 \endcode 
274 It is also possible to define object specific memory pools for each different type of RTOS object. In this model you define
275 the maximum number of a specific object type and its memory requirements. The RTOS then calculates and reserves the required
276 memory usage.
277  
278 The object specific model is again defined in the RTOS configuration file by enabling the "object specific memory" option
279 provided in each section of the configuration file:
280 \code
281 #define OS_SEMAPHORE_OBJ_MEM        1
282 #define OS_SEMAPHORE_NUM            1
283 \endcode
284 In the case of simple object which requires a fixed memory allocation we just need to define the maximum number of a given
285 object type. In the case of more complex objects such as threads we will need to define the required memory usage:
286 \code
287 #define OS_THREAD_OBJ_MEM           1
288 #define OS_THREAD_NUM               1
289 #define OS_THREAD_DEF_STACK_NUM     0
290 #define OS_THREAD_USER_STACK_SIZE   1024
291 \endcode 
292 To use the object specific memory allocation model with threads we must provide details of the overall thread memory usage.
293 Finally it is possible to statically allocate the thread stack memory. This is important for safety related systems where
294 memory usage has to be rigorously defined.
295
296
297 \subsection rtos2_tutorial_ex3 Exercise 3 - Memory Model
298
299
300 \section rtos2_tutorial_multi_inst Multiple Instances
301
302 One of the interesting possibilities of an RTOS is that you can create multiple running instances of the same base thread
303 code. For example, you could write a thread to control a UART and then create two running instances of the same thread code.
304 Here, each instance of the UART code could manage a different UART. Then we can create two instances of the thread assigned
305 to different thread handles. A parameter is also passed to allow each instance to identify which UART it is responsible for.
306 \code
307 #define UART1 (void *) 1UL
308 #define UART2 (void *) 2UL
309  
310 ThreadID_1_0 = osThreadNew (thread1, UART1, &ThreadAttr_Task1);
311 ThreadID_1_1 = osThreadNew (thread1, UART0, &ThreadAttr_Task1);
312 \endcode
313
314
315 \section rtos2_tutorial_thread_join Joinable Threads
316
317 A new feature in CMSIS-RTOS2 is the ability to create threads in a 'joinable' state. This allows a thead to be created and
318 executed as a standard thread. In addition, a second thread can join it by calling \ref osThreadJoin(). This will cause the
319 second thread to deschedule and remain in a waiting state until the thread which has been joined is terminated. This allows
320 a temporary joinable thread to be created, which would acquire a block of memory from the global memory pool, this thread
321 could perform some processing and then terminate, releasing the memory back to the memory pool. A joinable thread can be
322 created by setting the joinable attribute bit in the thread attributes structure as shown below:
323 \code
324 static const osThreadAttr_t ThreadAttr_worker = {
325         .attr_bits = osThreadJoinable
326 };
327 \endcode
328 Once the thread has been created, it will execute following the same rules as 'normal' threads. Any other thread can then
329 join it by using the OS call:
330 \code
331 osThreadJoin(<joinable_thread_handle>);
332 \endcode
333 Once \ref osThreadJoin() has been called, the thread will deschedule and enter a waiting state until the joinable thread has
334 terminated.
335
336
337 \subsection rtos2_tutorial_ex4 Exercise 4 - Joinable Threads
338
339
340 \section rtos2_tutorial_time_mgmt Time Management
341
342 As well as running your application code as threads, the RTOS also provides some timing services which can be accessed
343 through RTOS system calls. 
344
345
346 \subsection rtos2_tutorial_time_delay Time Delay
347
348 The most basic of these timing services is a simple timer delay function. This is an easy way of providing timing delays
349 within your application. Although the RTOS kernel size is quoted as 5 KB, features such as delay loops and simple scheduling
350 loops are often part of a non-RTOS application and would consume code bytes anyway, so the overhead of the RTOS can be less
351 than it immediately appears.
352 \code
353 void osDelay (uint32_t ticks)
354 \endcode
355 This call will place the calling thread into the WAIT_DELAY state for the specified number of milliseconds. The scheduler
356 will pass execution to the next thread in the READY state. 
357  
358 When the timer expires, the thread will leave the WAIT_DELAY  state and move to the READY state. The thread will resume
359 running when the scheduler moves it to the RUNNING state. If the thread then continues executing without any further
360 blocking OS calls, it will be descheduled at the end of its time slice and be placed in the ready state, assuming another
361 thread of the same priority is ready to run.
362
363
364 \subsection rtos2_tutorial_abs_time_delay Absolute Time Delay
365
366 In addition to the \ref osDelay() function which gives a relative time delay starting from the instant it is called, there
367 is also a delay function which halts a thread until a specific point in time:
368 \code
369 osStatus osDelayUntil (uint32_t ticks)   
370 \endcode
371 The \ref osDelayUntil() function will halt a thread until a specific value of kernel timer ticks is reached. There are a
372 number of kernel functions that allow you to read both the current SysTick count and the kernel ticks count.
373
374 | Kernel timer functions |
375 |------------------------|
376 | uint64_t \ref osKernelGetTickCount(void)     |
377 | uint32_t \ref osKernelGetTickFreq(void)      |
378 | uint32_t \ref osKernelGetSysTimerCount(void) |
379 | uint32_t \ref osKernelGetSysTimerFreq(void)  |
380
381
382 \subsection rtos2_tutorial_ex6 Exercise 6 - Time Management
383
384
385 \subsection rtos2_tutorial_virtual_timers Virtual Timers
386
387 The CMSIS-RTOS API can be used to define any number of virtual timers which act as count down timers. When they expire, they
388 will run a user call-back function to perform a specific action. Each timer can be configured as a one shot or repeat timer.
389 A virtual timer is created by first defining a timer structure:
390 \code
391 static const osThreadAttr_t ThreadAttr_app_main = {
392   const char * name // symbolic name of the timer
393   uin32_t attr_bits // None
394   void* cb_mem      // pointer to memory for control block
395   uint32_t cb_size  // size of memory control block
396 }
397 \endcode
398 This defines a name for the timer and the name of the call back function. The timer must then be instantiated by an RTOS
399 thread:
400 \code
401 osTimerId_t timer0_handle;
402 timer0_handle = osTimerNew(&callback, osTimerPeriodic,(void *)<parameter>, &timerAttr_timer0);
403 \endcode
404 This creates the timer and defines it as a periodic timer or a single shot timer (\ref osTimerOnce()). The next parameter
405 passes an argument to the call back function when the timer expires:
406 \code
407 osTimerStart (timer0_handle,0x100);
408 \endcode
409 The timer can then be started at any point in a thread the timer start function invokes the timer by its handle and defines
410 a count period in kernel ticks.
411
412
413 \subsection rtos2_tutorial_ex7 Exercise 7 - Virtual Timer
414
415
416 \subsection rtos2_tutorial_idle_thread Idle Thread
417
418 The final timer service provided by the RTOS isn't really a timer, but this is probably the best place to discuss it. If
419 during our RTOS program we have no thread running and no thread ready to run (e.g. they are all waiting on delay functions),
420 then the RTOS will start to run the Idle Thread. This thread is automatically created when the RTOS starts and runs at the
421 lowest priority. The Idle Thread function is located in the RTX_Config.c file:
422 \code 
423 __WEAK __NO_RETURN void osRtxIdleThread (void *argument) {
424   (void)argument;
425  
426   for (;;) {}
427 }
428 \endcode
429 You can add any code to this thread, but it has to obey the same rules as user threads. The simplest use of the idle demon
430 is to place the microcontroller into a low-power mode when it is not doing anything.
431 \code 
432 __WEAK __NO_RETURN void osRtxIdleThread (void *argument) {
433   (void)argument;
434  
435   for (;;) {
436     __WFE();
437   }
438 }
439 \endcode
440 What happens next depends on the power mode selected in the microcontroller. At a minimum, the CPU will halt until an
441 interrupt is generated by the SysTick timer and execution of the scheduler will resume. If there is a thread ready to run,
442 then execution of the application code will resume. Otherwise, the idle demon will be reentered and the system will go back
443 to sleep.
444
445
446 \subsection rtos2_tutorial_ex8 Exercise 8 - Idle Thread
447
448
449 \section rtos2_tutorial_interthread_com Inter-thread Communication
450
451 So far, we have seen how application code can be defined as independent threads and how we can access the timing services
452 provided by the RTOS. In a real application, we need to be able to communicate between threads in order to make an
453 application useful. To this end, a typical RTOS supports several different communication objects which can be used to link
454 the threads together to form a meaningful program. The CMSIS-RTOS2 API supports inter-thread communication with thread and
455 event flags, semaphores, mutexes, mailboxes and message queues. In the first section, the key concept was concurrency. In
456 this section, the key concept is synchronizing the activity of multiple threads.
457
458
459 \subsection rtos2_tutorial_thread_flags Thread Flags
460
461 Keil RTX5 supports up to thirty two thread flags for each thread. These thread flags are stored in the thread control block.
462 It is possible to halt the execution of a thread until a particular thread flag or group of thread flags are set by another
463 thread in the system.
464
465 The \ref osThreadFlagsWait() system calls will suspend execution of the thread and place it into the wait_evnt state.
466 Execution of the thread will not start until at least one the flags set in the \ref osThreadFlagsWait() API call have been
467 set. It is also possible to define a periodic timeout after which the waiting thread will move back to the ready state, so
468 that it can resume execution when selected by the scheduler. A value of \ref osWaitForever (0xFFFF) defines an infinite
469 timeout period.
470 \code
471 osEvent osThreadFlagsWait (int32_t flags,int32_t options,uint32_t timeout);
472 \endcode
473 The thread flag options are as follows:
474 | Options             | Description |
475 |---------------------|-------------|
476 | \ref osFlagsWaitAny | Wait for any flag to be set(default) |
477 | \ref osFlagsWaitAll | Wait for all flags to be set |
478 | \ref osFlagsNoClear | Do not clear flags that have been specified to wait for |
479
480 If a pattern of flags is specified, the thread will resume execution when any one of the specified flags is set (Logic OR).
481 If the \ref osFlagsWaitAll option is used, then all the flags in the pattern must be set (Logic AND). Any thread can set a
482 flag on any other thread and a thread may clear its own flags:
483 \code
484 int32_t osThredFlagsSet (osThreadId_t  thread_id, int32_t flags);
485 int32_t osThreadFlagsClear (int32_t signals);
486 \endcode
487
488
489 \subsection rtos2_tutorial_ex9 Exercise 9 - Thread Flags
490
491
492 \subsection rtos2_tutorial_event_flags Event Flags
493
494 Event flags operate in a similar fashion to thread flags but must be created and then act as a global RTOS object that can
495 be used by all the running threads.
496  
497 First, we need to create a set of event flags, this is a similar process to creating a thread. We define an event flag
498 attribute structure. The attribute structure defines an ASCII name string, attribute bits, and memory detention. If we are
499 using the static memory model.
500 \code
501 osEventFlagsAttr_t {
502   const char *name;   ///< name of the event flags
503   uint32_t attr_bits; ///< attribute bits (none)
504   void *cb_mem;       ///< memory for control block
505   uint32_t cb_size;   ///< size of provided memory for control block
506 };
507 \endcode
508 Next we need a handle to control access the event flags:
509 \code
510 osEventFlagsId_t EventFlag_LED;
511 \endcode
512 Then we can create the event flag object:
513 \code
514 EventFlag_LED = osEventFlagsNew(&EventFlagAttr_LED);
515 \endcode
516 Refer to \ref CMSIS_RTOS_EventFlags for more information.
517
518
519 \subsection rtos2_tutorial_ex10 Exercise 10 - Event Flags
520
521
522 \subsection rtos2_tutorial_semaphores Semaphores
523
524 Like thread flags, semaphores are a method of synchronizing activity between two or more threads. Put simply, a semaphore is
525 a container that holds a number of tokens. As a thread executes, it will reach an RTOS call to acquire a semaphore token. If
526 the semaphore contains one or more tokens, the thread will continue executing and the number of tokens in the semaphore will
527 be decremented by one. If there are currently no tokens in the semaphore, the thread will be placed in a waiting state until
528 a token becomes available. At any point in its execution, a thread may add a token to the semaphore causing its token count
529 to increment by one.
530
531 The diagram above illustrates the use of a semaphore to synchronize two threads. First, the semaphore must be created and
532 initialized with an initial token count. In this case the semaphore is initialized with a single token. Both threads will
533 run and reach a point in their code where they will attempt to acquire a token from the semaphore. The first thread to reach
534 this point will acquire the token from the semaphore and continue execution. The second thread will also attempt to acquire
535 a token, but as the semaphore is empty it will halt execution and be placed into a waiting state until a semaphore token is
536 available. 
537
538 Meanwhile, the executing thread can release a token back to the semaphore. When this happens, the waiting thread will
539 acquire the token and leave the waiting state for the ready state. Once in the ready state the scheduler will place the
540 thread into the run state so that thread execution can continue. While semaphores have a simple set of OS calls they can be
541 one of the more difficult OS objects to fully understand. In this section, we will first look at how to add semaphores to an
542 RTOS program and then go on to look at the most useful semaphore applications.
543
544 To use a semaphore in the CMSIS-RTOS you must first declare a semaphore attributes:
545 \code
546 osSemaphoreAttr_t {
547   const char *name;   ///< name of the semaphore
548   uint32_t attr_bits; ///< attribute bits (none)
549   void *cb_mem;       ///< memory for control block
550   uint32_t cb_size;   ///< size of provided memory for control block
551 };
552 \endcode
553 Next declare the semaphore handle:
554 \code
555 osSemaphoreId_t sem1;
556 \endcode
557 Then within a thread the semaphore container can be initialised with a number of tokens:
558 \code
559 sem1 = osSemaphoreNew(maxTokenCount,initalTokencount,&osSemaphoreAttr_t);
560 \endcode
561 It is important to understand that semaphore tokens may also be created and destroyed as threads run. So for example you can
562 initialise a semaphore with zero tokens and then use one thread to create tokens into the semaphore while another thread
563 removes them. This allows you to design threads as producer and consumer threads.
564
565 Once the semaphore is initialized, tokens may be acquired and sent to the semaphore in a similar fashion to event flags. The
566 \ref osSemaphoreAcquire() call is used to block a thread until a semaphore token is available. A timeout period may also be
567 specified with 0xFFFF being an infinite wait.
568 \code
569 osStatus osSemaphoreAcquire(osSemaphoreId_t semaphore_id, uint32_t ticks);
570 \endcode
571 Once the thread has finished using the semaphore resource, it can send a token to the semaphore container:
572 \code
573 osStatus osSemaphoreRelease(osSemaphoreId_t semaphore_id);
574 \endcode
575 All semaphore functions are listed in the \ref CMSIS_RTOS_SemaphoreMgmt "reference".
576
577
578 \subsubsection rtos2_tutorial_ex11 Exercise 11 - Semaphore Signalling
579
580
581 \subsubsection rtos2_tutorial_sem_usage Using Semaphores
582
583 Although semaphores have a simple set of OS calls, they have a wide range of synchronizing applications. This makes them
584 perhaps the most challenging RTOS object to understand. In this section we, will look at the most common uses of semaphores.
585 These are taken from free book
586 <a href="https://greenteapress.com/wp/semaphores/" target="_blank">"The Little Book Of Semaphores" by Allen B. Downey</a>.
587
588
589 \subsubsection rtos2_tutorial_sem_sig Signalling
590
591 Synchronizing the execution of two threads is the simplest use of a semaphore:
592 \code
593 osSemaphoreId_t sem1;
594 static const osSemaphoreAttr_t semAttr_SEM1 = {
595     .name = "SEM1",
596 };
597  
598 void thread1(void) {
599   sem1 = osSemaphoreNew(5, 0, &semAttr_SEM1);
600   while (1) {
601     FuncA();
602     osSemaphoreRelease(sem1)
603   }
604 }
605  
606 void task2(void) {
607
608   while (1) {
609     osSemaphoreAcquire(sem1, osWaitForever) FuncB();
610   }
611 }
612 \endcode
613 In this case the semaphore is used to ensure that the code in \c FuncA() is executed before the code in \c FuncB().
614
615
616 \subsubsection rtos2_tutorial_sem_multi Multiplex
617
618 A multiplex is used to limit the number of threads that can access a critical section of code. For example, this could be a
619 routine that accesses memory resources and can only support a limited number of calls.
620 \code
621 osSemaphoreId_t multiplex;
622 static const osSemaphoreAttr_t semAttr_Multiplex = {
623     .name = "SEM1",
624 };
625  
626 void thread1(void) {
627   multiplex = osSemaphoreCreate(5, 5, &semAttr_Multiplex);
628   while (1) {
629     osSemaphoreAcquire(multiplex, osWaitForever);
630     processBuffer();
631     osSemaphoreRelease(multiplex);
632   }
633 }
634 \endcode
635 In this example we initialise the multiplex semaphore with five tokens. Before a thread can call the \c processBuffer()
636 function, it must acquire a semaphore token. Once the function has completed, the token is sent back to the semaphore. If
637 more than five threads are attempting to call \c processBuffer(), the sixth must wait until a thread has finished with
638 \c processBuffer() and returns its token. Thus, the multiplex semaphore ensures that a maximum of five threads can call the
639 \c processBuffer() function "simultaneously".
640
641
642 \subsubsection rtos2_tutorial_ex12 Exercise 12 - Multiplex
643
644
645 \subsubsection rtos2_tutorial_sem_rend Rendezvous
646
647 A more generalised form of semaphore signalling is a rendezvous. A rendezvous ensures that two threads reach a certain point
648 of execution. Neither may continue until both have reached the rendezvous point.
649 \code
650 osSemaphoreId_t arrived1, arrived2;
651 static const osSemaphoreAttr_t semAttr_Arrived1 = {
652     .name = "Arr1",
653 };
654  
655 static const osSemaphoreAttr_t semAttr_Arrived2 = {
656     .name = "Arr2",
657 };
658  
659 void thread1(void) {
660   arrived1 = osSemaphoreNew(2, 0);
661   arrived1 = osSemaphoreNew(2, 0);
662   while (1) {
663     FuncA1();
664     osSemaphoreRelease(arrived1);
665     osSemaphoreAcquire(arrived2, osWaitForever);
666     FuncA2();
667   }
668 }
669  
670 void thread2(void) {
671   while (1) {
672     FuncB1();
673     os_sem_Release(arrived2);
674     os_sem_Acquire(arrived1, osWaitForever);
675     FuncB2();
676   }
677 }
678 \endcode
679 In the above case, the two semaphores will ensure that both threads will rendezvous and then proceed to execute \c FuncA2()
680 and \c FuncB2().
681
682 \subsubsection rtos2_tutorial_sem_barr_turn Barrier Turnstile
683
684 Although a rendezvous is very useful for synchronising the execution of code, it only works for two functions. A barrier is
685 a more generalised form of rendezvous which works to synchronise multiple threads.
686 \code
687 osSemaphoreId_t count, barrier;
688 static const osSemaphoreAttr_t semAttr_Counter = {
689     .name = "Counter",
690 };
691  
692 static const osSemaphoreAttr_t semAttr_Barier = {
693     .name = "Barrier",
694 };
695  
696 unsigned int count;
697  
698 void thread1(void) {
699   Turnstile_In = osSemaphoreNew(5, 0, &semAttr_SEM_In);
700   Turnstile_Out = osSemaphoreNew(5, 1, &semAttr_SEM_Out);
701   Mutex = osSemaphoreNew(1, 1, &semAttr_Mutex);
702   while (1) {
703     osSemaphoreAcquire(Mutex, osWaitForever); // Allow one task at a time to
704                                               // access the first turnstile
705     count = count + 1; // Increment count
706     if (count == 5) {
707       osSemaphoreAcquire(Turnstile_Out,
708                          osWaitForever); // Lock the second turnstile
709       osSemaphoreRelease(Turnstile_In);  // Unlock the first turnstile
710     }
711     osSemaphoreRelease(Mutex); // Allow other tasks to access the turnstile
712     osSemaphoreAcquire(Turnstile_In, osWaitForever); // Turnstile Gate
713     osSemaphoreRelease(Turnstile_In);
714     critical_Function();
715   }
716 }
717 \endcode
718 In this code, we use a global variable to count the number of threads which have arrived at the barrier. As each function
719 arrives at the barrier it will wait until it can acquire a token from the counter semaphore. Once acquired, the count
720 variable will be incremented by one. Once we have incremented the count variable, a token is sent to the counter semaphore
721 so that other waiting threads can proceed. Next, the barrier code reads the count variable. If this is equal to the number
722 of threads which are waiting to arrive at the barrier, we send a token to the barrier semaphore. 
723
724 In the example above we are synchronising five threads. The first four threads will increment the count variable and then
725 wait at the barrier semaphore. The fifth and last thread to arrive will increment the count variable and send a token to the
726 barrier semaphore. This will allow it to immediately acquire a barrier semaphore token and continue execution. After passing
727 through the barrier, it immediately sends another token to the barrier semaphore. This allows one of the other waiting
728 threads to resume execution. This thread places another token in the barrier semaphore which triggers another waiting thread
729 and so on. This final section of the barrier code is called a turnstile because it allows one thread at a time to pass the
730 barrier. In our model of concurrent execution this means that each thread waits at the barrier until the last arrives then
731 the all resume simultaneously. In the following exercise we create five instances of one thread containing barrier code.
732 However, the barrier could be used to synchronise five unique threads.
733
734
735 \subsubsection rtos2_tutorial_ex14 Exercise 14 - Semaphore Barrier
736
737
738 \subsubsection rtos2_tutorial_sem_caveats Semaphore Caveats
739
740 Semaphores are an extremely useful feature of any RTOS. However semaphores can be misused. You must always remember that the
741 number of tokens in a semaphore is not fixed. During the runtime of a program semaphore tokens may be created and destroyed.
742 Sometimes this is useful, but if your code depends on having a fixed number of tokens available to a semaphore you must be
743 very careful to always return tokens back to it. You should also rule out the possibility of accidently creating additional
744 new tokens.
745
746
747 \subsection rtos2_tutorial_mutex Mutex
748
749 Mutex stands for “Mutual Exclusion”. In reality, a mutex is a specialized version of semaphore. Like a semaphore, a mutex is
750 a container for tokens. The difference is that a mutex can only contain one token which cannot be created or destroyed. The
751 principle use of a mutex is to control access to a chip resource such as a peripheral. For this reason a mutex token is
752 binary and bounded. Apart from this it really works in the same way as a semaphore. First of all we must declare the mutex
753 container and initialize the mutex:
754 \code
755 osMutexId_t uart_mutex;
756  
757 osMutexAttr_t {
758   const char *name;   ///< name of the mutex
759   uint32_t attr_bits; ///< attribute bits
760   void *cb_mem;       ///< memory for control block
761   uint32_t cb_size;   ///< size of provided memory for control block
762 };
763 \endcode
764 When a mutex is created its functionality can be modified by setting the following attribute bits:
765 | Bitmask                 | Description |
766 |-------------------------|-------------|
767 | \ref osMutexRecursive   | The same thread can consume a mutex multiple times without locking itself.        |
768 | \ref osMutexPrioInherit | While a thread owns the mutex it cannot be preempted by a higher priority thread. |
769 | \ref osMutexRobust      | Notify threads that acquire a mutex that the previous owner was terminated.       |
770
771 Once declared the mutex must be created in a thread.
772 \code
773 uart_mutex = osMutexNew(&MutexAttr);
774 \endcode
775 Then any thread needing to access the peripheral must first acquire the mutex token:
776 \code
777 osMutexAcquire(osMutexId_t mutex_id,uint32_t ticks);
778 \endcode
779 Finally, when we are finished with the peripheral the mutex must be released:
780 \code
781 osMutexRelease(osMutexId_t mutex_id);
782 \endcode
783 Mutex use is much more rigid than semaphore use, but is a much safer mechanism when controlling absolute access to
784 underlying chip registers.
785
786
787 \subsubsection rtos2_tutorial_ex15 Exercise 15 - Mutex
788
789
790 \subsubsection rtos2_tutorial_mutex_caveats Mutex Caveats
791
792 Clearly, you must take care to return the mutex token when you are finished with the chip resource, or you will have
793 effectively prevented any other thread from accessing it. You must also be extremely careful about using the
794 \ref osThreadTerminate() call on functions which control a mutex token. Keil RTX5 is designed to be a small footprint RTOS
795 so that it can run on even the very small Cortex-M microcontrollers. Consequently, there is no thread deletion safety. This
796 means that if you delete a thread which is controlling a mutex token, you will destroy the mutex token and prevent any
797 further access to the guarded peripheral.
798
799
800 \subsection rtos2_tutorial_data_exchange Data Exchange
801
802 So far, all of the inter-thread communication methods have only been used to trigger execution of threads; they do not
803 upport the exchange of program data between threads. Clearly, in a real program we will need to move data between threads.
804 This could be done by reading and writing to globally declared variables. In anything but a very simple program, trying to
805 guarantee data integrity would be extremely difficult and prone to unforeseen errors. The exchange of data between threads
806 needs a more formal asynchronous method of communication. 
807
808 CMSIS-RTOS provides two methods of data transfer between threads. The first method is a message queue which creates a
809 buffered data 'pipe' between two threads. The message queue is designed to transfer integer values.
810
811 The second form of data transfer is a mail queue. This is very similar to a message queue except that it transfers blocks of
812 data rather than a single integer.
813
814 Message and mail queues both provide a method for transferring data between threads. This allows you to view your design as
815 a collection of objects (threads) interconnected by data flows. The data flow is implemented by message and mail queues.
816 This provides both a buffered transfer of data and a well defined communication interface between threads. Starting with a
817 system level design based on threads connected by mail and message queues allows you to code different subsystems of your
818 project, especially useful if you are working in a team. Also as each thread has well defined inputs and outputs it is easy
819 to isolate for testing and code reuse.
820
821
822 \subsubsection rtos2_tutorial_msg_queue Message Queue
823
824 To setup a message queue we first need to allocate the memory resources:
825 \code
826 osMessageQId_t Q_LED;
827  
828 osMessageQueueAttr_t {
829   const char *name;   ///< name of the message queue
830   uint32_t attr_bits; ///< attribute bits
831   void *cb_mem;       ///< memory for control block
832   uint32_t cb_size;   ///< size of provided memory for control block
833   void *mq_mem;       ///< memory for data storage
834   uint32_t mq_size;   ///< size of provided memory for data storage
835 };
836 \endcode
837 Once the message queue handle and attributes have been declared we can create the message queue in a thread:
838 \code
839 Q_LED = osMessageNew(DepthOfMesageQueue,WidthOfMessageQueue,&osMessageQueueAttr);
840 \endcode
841 Once the message queue has been created we can put data into the queue from one thread:
842 \code
843 osMessageQueuePut(Q_LED,&dataIn,messagePrioriy,osWaitForever);
844 \endcode
845 and then read if from the queue in another:
846 \code
847 result = osMessageQueueGet(Q_LED,&dataOut,messagePriority,osWaitForever);
848 \endcode
849
850
851 \subsubsection rtos2_tutorial_ex16 Exercise 16 - Message Queue
852
853
854 \subsubsection rtos2_tutorial_ext_msg_queue Extended Message Queue
855
856 In the last example we defined a word wide message queue. If you need to send a larger amount of data it is also possible to
857 define a message queue where each slot can hold more complex data. First, we can define a structure to hold our message
858 data:
859 \code
860 typedef struct {
861   uint32_t duration;
862   uint32_t ledNumber;
863   uint8_t priority;
864 } message_t;
865 \endcode
866 Then we can define a message queue which is formatted to receive this type of message:
867 \code
868 Q_LED = osMessageQueueNew(16,sizeof(message_t),&queueAttr_Q_LED );      
869 \endcode
870
871
872 \subsubsection rtos2_tutorial_ex17 Exercise 17 - Message Queue
873
874
875 \subsubsection rtos2_tutorial_mem_pool Memory Pool
876
877 We can design a message queue to support the transfer of large amounts of data. However, this method has an overhead in that
878 we are "moving" the data in the queue. In this section, we will look at designing a more efficient "zero copy" mailbox where
879 the data remains static. CMSIS-RTOS2 supports the dynamic allocation of memory in the form of a fixed block memory pool.
880 First, we can declare the memory pool attributes:
881 \code
882 osMemoryPoolAttr_t {
883   const char *name;   ///< name of the memory pool
884   uint32_t attr_bits; ///< attribute bits
885   void *cb_mem;       ///< memory for control block
886   uint32_t cb_size;   ///< size of provided memory for control block
887   void *mp_mem;       ///< memory for data storage
888   uint32_t mp_size;   ///< size of provided memory for data storage
889 } osMemoryPoolAttr_t;
890 \endcode
891 And a handle for the memory pool:
892 \code
893 osMemoryPoolId_t mpool;
894 \endcode
895 For the memory pool itself, we need to declare a structure which contains the memory elements we require in each memory pool
896 lot:
897 \code
898 typedef struct {
899   uint8_t LED0;
900   uint8_t LED1;
901   uint8_t LED2;
902   uint8_t LED3;
903 } memory_block_t;
904 \endcode
905 Then we can create a memory pool in our application code:
906 \code
907 mpool = osMemoryPoolNew(16, sizeof(message_t),&memorypoolAttr_mpool);
908 \endcode
909 Now we can allocate a memory pool slot within a thread:
910 \code
911 memory_block_t *led_data;
912 *led_data = (memory_block_t *) osMemoryPoolAlloc(mPool,osWaitForever);
913 \endcode
914 and then populate it with data:
915 \code
916         led_data->LED0 = 0;
917         led_data->LED1 = 1;
918         led_data->LED2 = 2;
919         led_data->LED3 = 3;
920 \endcode
921 It is then possible to place the pointer to the memory block in a message queue:
922 \code
923 osMessagePut(Q_LED,(uint32_t)led_data,osWaitForever);
924 \endcode
925 The data can now be accessed by another task:
926 \code
927 osEvent event;
928 memory_block_t *received;
929 event = osMessageGet(Q_LED, osWatiForever);
930 *received = (memory_block *)event.value.p;
931 led_on(received->LED0);
932 \endcode
933 Once the data in the memory block has been used, the block must be released back to the memory pool for reuse.
934 \code
935 osPoolFree(led_pool,received);
936 \endcode
937 To create a zero copy mail box system, we can combine a memory pool to store the data with a message queue which is used to
938 transfer a pointer o the allocated memory pool slot. This way the message data stays static and we pass a pointer between
939 threads.
940
941
942 \subsubsection rtos2_tutorial_ex18 Exercise 18 - Zero Copy Mailbox
943
944
945 \section rtos2_tutorial_config Configuration
946
947 So far we have looked at the CMSIS-RTOS2 API. This includes thread management functions, time management and inter-thread
948 communication. Now that we have a clear idea of exactly what the RTOS kernel is capable of, we can take a more detailed look
949 at the configuration file.
950
951 RTX_Config.h is the central configuration file for all of the Cortex-M based microcontrollers.  Like the other configuration
952 files, it is a template file which presents all the necessary configurations as a set of menu options (when viewed in
953 Configuration Wizard view).
954
955
956 \subsection rtos2_tutorial_config_sys System Configuration
957
958 Before we discuss the settings in the system configuration section, it is worth mentioning what is missing. In earlier
959 versions of CMSIS-RTOS, it was necessary to define the CPU frequency as part of the RTOS configuration. In CMSIS-RTOS2, the
960 CPU frequency is now taken from the "SystemCoreClock" variable which is set as part of the CMSIS-Core system startup code.
961 If you are working with a new microcontroller you will need to check that this value is being set correctly.
962
963 As we have seen earlier, we can set the amount of memory allocated to the "Global Dynamic Memory Pool". Next, we can define
964 the tick frequency in Hertz. This defines the SysTick interrupt rate and is set to 1 ms by default. Generally, I would leave
965 this frequency at its default setting. However, processor clock speeds are getting ever faster. If you are using a high
966 performance device you may consider using a faster tick rate.
967
968 "Round Robin Thread" switching is also enabled by default in this section. Again, I would recommend leaving these settings
969 in their default state unless you have a strong requirement to change them. The system configuration settings also allow us
970 to control the range of messages sent to the event recorder as the RTOS runs.
971
972 Finally, if we are setting thread flags from an interrupt they are held in a queue until they are processed. Depending on
973 your application you may need to increase the size of this queue.
974
975
976 \subsection rtos2_tutorial_config_thread Thread Configuration
977
978 In the Thread Configuration section, we define the basic resources which will be required by the CMSIS-RTOS2 threads. For
979 each thread we allocate a "default thread stack space" (by default, this is 200 bytes). As you create threads, this memory
980 will be allocated from the Global Dynamic Mmemory Pool. However, if we enable Object specific memory allocation the RTOS
981 will define a memory region which is dedicated to thread usage only. If you switch to object specific memory allocation, it
982 is necessary to provide details about the number and size of threads memory so the RTOS can calculate the maximum memory
983 requirement.
984
985 For object specific memory allocation, we must define the maximum number of user threads (don’t count the idle
986 or timer threads) which will be running. We must also define the number of threads which have a default stack size and also
987 the total amount of memory required by threads with custom tack sizes. Once we have defined the memory used by user threads,
988 we can allocate memory to the idle thread. During development, CMSIS-RTOS can trap stack overflows. When this option is
989 enabled, an overflow of a thread stack space will cause the RTOS kernel to call the \ref osRtxErrorNotify() function which
990 is located in the RTX_Config.c file. This function gets an error code and then sits in an infinite loop. The stack checking
991 option is intended for use during debugging and should be disabled on the final application to minimize the kernel overhead.
992 However, it is possible to modify the \ref osRtxErrorNotify() function if enhanced error protection is required in the final
993 release.
994 \code
995 // OS Error Callback function
996 __WEAK uint32_t osRtxErrorNotify (uint32_t code, void *object_id) {
997   (void)object_id;
998
999   switch (code) {
1000     case osRtxErrorStackUnderflow:
1001       // Stack overflow detected for thread (thread_id=object_id)
1002       break;
1003     case osRtxErrorISRQueueOverflow:
1004       // ISR Queue overflow detected when inserting object (object_id)
1005       break;
1006     case osRtxErrorTimerQueueOverflow:
1007       // User Timer Callback Queue overflow detected for timer (timer_id=object_id)
1008       break;
1009     case osRtxErrorClibSpace:
1010       // Standard C/C++ library libspace not available: increase OS_THREAD_LIBSPACE_NUM
1011       break;
1012     case osRtxErrorClibMutex:
1013       // Standard C/C++ library mutex initialization failed
1014       break;
1015     default:
1016       // Reserved
1017       break;
1018   }
1019   for (;;) {}
1020 //return 0U;
1021 }
1022 \endcode
1023 It is also possible to monitor the maximum stack memory usage during run time. If you check the "Stack Usage Watermark"
1024 option, a pattern (0xCC) is written into each stack space. During runtime, this watermark is used to calculate the maximum
1025 memory usage. In Arm Keil MDK, this figure is reported in the threads section of the View - Watch Window - RTX RTOS window.
1026  
1027 This section also allows us to select whether the threads are running in privileged or unprivileged mode. The last option
1028 allows us to define the processor operating mode for the user threads. If you want an easy life, leave this set to
1029 "privileged mode" and you will have full access to all the processor features. However, if you are writing a safety critical
1030 or secure application then "unprivileged mode" can be used to prevent thread access to critical processor registers limiting
1031 run time errors or attempts at intrusion.
1032
1033
1034 \subsection rtos2_tutorial_config_sys_timer System Timer Configuration
1035
1036 The default timer for use with CMSIS-RTOS is the Cortex-M SysTick timer which is present on nearly all Cortex-M processors.
1037 The input to the SysTick timer will generally be the CPU clock. It is possible to use a different timer by overloading the
1038 kernel timer functions as outlined explained in the \ref CMSIS_RTOS_TickAPI documentation.
1039
1040
1041 \section rtos2_tutorial_conclusion Conclusion
1042
1043 In this tutorial, we have worked our way through the CMSIS-RTOS2 API and introduced some of the key concepts associated with
1044 using an RTOS. The only real way to learn how to develop with an RTOS is to actually use one in a real project. 
1045 */