3 * Copyright (C) 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved.
5 * Permission is hereby granted, free of charge, to any person obtaining a copy of
6 * this software and associated documentation files (the "Software"), to deal in
7 * the Software without restriction, including without limitation the rights to
8 * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
9 * the Software, and to permit persons to whom the Software is furnished to do so,
10 * subject to the following conditions:
12 * The above copyright notice and this permission notice shall be included in all
13 * copies or substantial portions of the Software.
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
17 * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
18 * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
19 * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
20 * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 * http://www.FreeRTOS.org
23 * http://aws.amazon.com/freertos
29 The tasks defined on this page demonstrate the use of recursive mutexes.
31 For recursive mutex functionality the created mutex should be created using
32 xSemaphoreCreateRecursiveMutex(), then be manipulated
33 using the xSemaphoreTakeRecursive() and xSemaphoreGiveRecursive() API
36 This demo creates three tasks all of which access the same recursive mutex:
38 prvRecursiveMutexControllingTask() has the highest priority so executes
39 first and grabs the mutex. It then performs some recursive accesses -
40 between each of which it sleeps for a short period to let the lower
41 priority tasks execute. When it has completed its demo functionality
42 it gives the mutex back before suspending itself.
44 prvRecursiveMutexBlockingTask() attempts to access the mutex by performing
45 a blocking 'take'. The blocking task has a lower priority than the
46 controlling task so by the time it executes the mutex has already been
47 taken by the controlling task, causing the blocking task to block. It
48 does not unblock until the controlling task has given the mutex back,
49 and it does not actually run until the controlling task has suspended
50 itself (due to the relative priorities). When it eventually does obtain
51 the mutex all it does is give the mutex back prior to also suspending
52 itself. At this point both the controlling task and the blocking task are
55 prvRecursiveMutexPollingTask() runs at the idle priority. It spins round
56 a tight loop attempting to obtain the mutex with a non-blocking call. As
57 the lowest priority task it will not successfully obtain the mutex until
58 both the controlling and blocking tasks are suspended. Once it eventually
59 does obtain the mutex it first unsuspends both the controlling task and
60 blocking task prior to giving the mutex back - resulting in the polling
61 task temporarily inheriting the controlling tasks priority.
64 /* Scheduler include files. */
69 /* Demo app include files. */
72 /* Priorities assigned to the three tasks. */
73 #define recmuCONTROLLING_TASK_PRIORITY ( tskIDLE_PRIORITY + 2 )
74 #define recmuBLOCKING_TASK_PRIORITY ( tskIDLE_PRIORITY + 1 )
75 #define recmuPOLLING_TASK_PRIORITY ( tskIDLE_PRIORITY + 0 )
77 /* In this version the tick period is very long, so the short delay cannot be
78 for too many ticks, or the check task will execute and find that the recmutex
79 tasks have not completed their functionality and then signal an error. The
80 delay does however have to be long enough to allow the lower priority tasks
81 a chance of executing - this is basically achieved by reducing the number
82 of times the loop that takes/gives the recursive mutex executes. */
83 #define recmuMAX_COUNT ( 2 )
84 #define recmuSHORT_DELAY ( 20 )
85 #define recmuNO_DELAY ( ( TickType_t ) 0 )
86 #define recmuFIVE_TICK_DELAY ( ( TickType_t ) 5 )
88 /* The three tasks as described at the top of this file. */
89 static void prvRecursiveMutexControllingTask( void *pvParameters );
90 static void prvRecursiveMutexBlockingTask( void *pvParameters );
91 static void prvRecursiveMutexPollingTask( void *pvParameters );
93 /* The mutex used by the demo. */
94 static SemaphoreHandle_t xMutex;
96 /* Variables used to detect and latch errors. */
97 static volatile portBASE_TYPE xErrorOccurred = pdFALSE, xControllingIsSuspended = pdFALSE, xBlockingIsSuspended = pdFALSE;
98 static volatile unsigned portBASE_TYPE uxControllingCycles = 0, uxBlockingCycles = 0, uxPollingCycles = 0;
100 /* Handles of the two higher priority tasks, required so they can be resumed
102 static TaskHandle_t xControllingTaskHandle, xBlockingTaskHandle, xPollingTaskHandle;
104 /*-----------------------------------------------------------*/
106 void vStartRecursiveMutexTasks( void )
108 /* Just creates the mutex and the three tasks. */
110 xMutex = xSemaphoreCreateRecursiveMutex();
112 /* vQueueAddToRegistry() adds the mutex to the registry, if one is
113 in use. The registry is provided as a means for kernel aware
114 debuggers to locate mutex and has no purpose if a kernel aware debugger
115 is not being used. The call to vQueueAddToRegistry() will be removed
116 by the pre-processor if configQUEUE_REGISTRY_SIZE is not defined or is
117 defined to be less than 1. */
118 vQueueAddToRegistry( ( QueueHandle_t ) xMutex, "Recursive_Mutex" );
123 xTaskCreate( prvRecursiveMutexControllingTask, "Rec1Ctrl", configMINIMAL_STACK_SIZE, NULL, recmuCONTROLLING_TASK_PRIORITY, &xControllingTaskHandle );
124 xTaskCreate( prvRecursiveMutexBlockingTask, "Rec2Blck", configMINIMAL_STACK_SIZE, NULL, recmuBLOCKING_TASK_PRIORITY, &xBlockingTaskHandle );
125 xTaskCreate( prvRecursiveMutexPollingTask, "Rec3Poll", configMINIMAL_STACK_SIZE, NULL, recmuPOLLING_TASK_PRIORITY, &xPollingTaskHandle );
128 /*-----------------------------------------------------------*/
130 static void prvRecursiveMutexControllingTask( void *pvParameters )
132 unsigned portBASE_TYPE ux;
134 /* Just to remove compiler warning. */
135 ( void ) pvParameters;
139 /* Should not be able to 'give' the mutex, as we have not yet 'taken'
140 it. The first time through, the mutex will not have been used yet,
141 subsequent times through, at this point the mutex will be held by the
143 if( xSemaphoreGiveRecursive( xMutex ) == pdPASS )
145 xErrorOccurred = pdTRUE;
148 for( ux = 0; ux < recmuMAX_COUNT; ux++ )
150 /* We should now be able to take the mutex as many times as
153 The first time through the mutex will be immediately available, on
154 subsequent times through the mutex will be held by the polling task
155 at this point and this Take will cause the polling task to inherit
156 the priority of this task. In this case the block time must be
157 long enough to ensure the polling task will execute again before the
158 block time expires. If the block time does expire then the error
159 flag will be set here. */
160 if( xSemaphoreTakeRecursive( xMutex, recmuFIVE_TICK_DELAY ) != pdPASS )
162 xErrorOccurred = pdTRUE;
165 /* Ensure the other task attempting to access the mutex (and the
166 other demo tasks) are able to execute to ensure they either block
167 (where a block time is specified) or return an error (where no
168 block time is specified) as the mutex is held by this task. */
169 vTaskDelay( recmuSHORT_DELAY );
172 /* For each time we took the mutex, give it back. */
173 for( ux = 0; ux < recmuMAX_COUNT; ux++ )
175 /* Ensure the other task attempting to access the mutex (and the
176 other demo tasks) are able to execute. */
177 vTaskDelay( recmuSHORT_DELAY );
179 /* We should now be able to give the mutex as many times as we
180 took it. When the mutex is available again the Blocking task
181 should be unblocked but not run because it has a lower priority
182 than this task. The polling task should also not run at this point
183 as it too has a lower priority than this task. */
184 if( xSemaphoreGiveRecursive( xMutex ) != pdPASS )
186 xErrorOccurred = pdTRUE;
189 #if configUSE_PREEMPTION == 0
194 /* Having given it back the same number of times as it was taken, we
195 should no longer be the mutex owner, so the next give should fail. */
196 if( xSemaphoreGiveRecursive( xMutex ) == pdPASS )
198 xErrorOccurred = pdTRUE;
201 /* Keep count of the number of cycles this task has performed so a
202 stall can be detected. */
203 uxControllingCycles++;
205 /* Suspend ourselves so the blocking task can execute. */
206 xControllingIsSuspended = pdTRUE;
207 vTaskSuspend( NULL );
208 xControllingIsSuspended = pdFALSE;
211 /*-----------------------------------------------------------*/
213 static void prvRecursiveMutexBlockingTask( void *pvParameters )
215 /* Just to remove compiler warning. */
216 ( void ) pvParameters;
220 /* This task will run while the controlling task is blocked, and the
221 controlling task will block only once it has the mutex - therefore
222 this call should block until the controlling task has given up the
223 mutex, and not actually execute past this call until the controlling
224 task is suspended. */
225 if( xSemaphoreTakeRecursive( xMutex, portMAX_DELAY ) == pdPASS )
227 if( xControllingIsSuspended != pdTRUE )
229 /* Did not expect to execute until the controlling task was
231 xErrorOccurred = pdTRUE;
235 /* Give the mutex back before suspending ourselves to allow
236 the polling task to obtain the mutex. */
237 if( xSemaphoreGiveRecursive( xMutex ) != pdPASS )
239 xErrorOccurred = pdTRUE;
242 xBlockingIsSuspended = pdTRUE;
243 vTaskSuspend( NULL );
244 xBlockingIsSuspended = pdFALSE;
249 /* We should not leave the xSemaphoreTakeRecursive() function
250 until the mutex was obtained. */
251 xErrorOccurred = pdTRUE;
254 /* The controlling and blocking tasks should be in lock step. */
255 if( uxControllingCycles != ( uxBlockingCycles + 1 ) )
257 xErrorOccurred = pdTRUE;
260 /* Keep count of the number of cycles this task has performed so a
261 stall can be detected. */
265 /*-----------------------------------------------------------*/
267 static void prvRecursiveMutexPollingTask( void *pvParameters )
269 /* Just to remove compiler warning. */
270 ( void ) pvParameters;
274 /* Keep attempting to obtain the mutex. We should only obtain it when
275 the blocking task has suspended itself, which in turn should only
276 happen when the controlling task is also suspended. */
277 if( xSemaphoreTakeRecursive( xMutex, recmuNO_DELAY ) == pdPASS )
279 /* Is the blocking task suspended? */
280 if( ( xBlockingIsSuspended != pdTRUE ) || ( xControllingIsSuspended != pdTRUE ) )
282 xErrorOccurred = pdTRUE;
286 /* Keep count of the number of cycles this task has performed
287 so a stall can be detected. */
290 /* We can resume the other tasks here even though they have a
291 higher priority than the polling task. When they execute they
292 will attempt to obtain the mutex but fail because the polling
293 task is still the mutex holder. The polling task (this task)
294 will then inherit the higher priority. The Blocking task will
295 block indefinitely when it attempts to obtain the mutex, the
296 Controlling task will only block for a fixed period and an
297 error will be latched if the polling task has not returned the
298 mutex by the time this fixed period has expired. */
299 vTaskResume( xBlockingTaskHandle );
300 #if configUSE_PREEMPTION == 0
304 vTaskResume( xControllingTaskHandle );
305 #if configUSE_PREEMPTION == 0
309 /* The other two tasks should now have executed and no longer
311 if( ( xBlockingIsSuspended == pdTRUE ) || ( xControllingIsSuspended == pdTRUE ) )
313 xErrorOccurred = pdTRUE;
316 /* Release the mutex, disinheriting the higher priority again. */
317 if( xSemaphoreGiveRecursive( xMutex ) != pdPASS )
319 xErrorOccurred = pdTRUE;
322 #if configUSE_PREEMPTION == 0
328 #if configUSE_PREEMPTION == 0
335 /*-----------------------------------------------------------*/
337 /* This is called to check that all the created tasks are still running. */
338 portBASE_TYPE xAreRecursiveMutexTasksStillRunning( void )
340 portBASE_TYPE xReturn;
341 static unsigned portBASE_TYPE uxLastControllingCycles = 0, uxLastBlockingCycles = 0, uxLastPollingCycles = 0;
343 /* Is the controlling task still cycling? */
344 if( uxLastControllingCycles == uxControllingCycles )
346 xErrorOccurred = pdTRUE;
350 uxLastControllingCycles = uxControllingCycles;
353 /* Is the blocking task still cycling? */
354 if( uxLastBlockingCycles == uxBlockingCycles )
356 xErrorOccurred = pdTRUE;
360 uxLastBlockingCycles = uxBlockingCycles;
363 /* Is the polling task still cycling? */
364 if( uxLastPollingCycles == uxPollingCycles )
366 xErrorOccurred = pdTRUE;
370 uxLastPollingCycles = uxPollingCycles;
373 if( xErrorOccurred == pdTRUE )