7 · 原书 260–291 页资源管理
7.1本章引言与范围
在多任务系统中,若一个任务开始访问某资源、但在被移出运行态之前尚未完成访问,就可能出错。若任务把资源留在不一致状态,其他任务或中断再访问同一资源,就可能导致数据损坏或类似问题。示例如下:
7.1.1访问外设
设想两个任务尝试写 LCD 的场景:① Task A 执行,开始向 LCD 写字符串“Hello world”;② 刚输出开头“Hello w”就被 Task B 抢占;③ Task B 向 LCD 写“Abort, Retry, Fail?”后进入阻塞态;④ Task A 从被抢占处继续,输出剩余字符“orld”。LCD 最终显示损坏字符串“Hello wAbort, Retry, Fail?orld”。
7.1.2读-改-写操作
清单 111 给出一行 C 代码及其典型汇编翻译:先把 PORTA 的值从内存读入寄存器,在寄存器内修改,再写回内存。这称为读-改-写操作。
/* The C code being compiled. */
PORTA |= 0x01;
/* The assembly code produced when the C code is compiled. */
LOAD R1,[#PORTA] ; Read a value from PORTA into R1
MOVE R2,#0x01 ; Move the absolute constant 1 into R2
OR R1,R2 ; Bitwise OR R1 (PORTA) with R2 (constant 1)
STORE R1,[#PORTA] ; Store the new value back to PORTA这是“非原子”操作,因为完成它需要多条指令、可被打断。设想两个任务尝试更新内存映射寄存器 PORTA:① Task A 把 PORTA 值读入寄存器(操作的读部分);② 尚未完成同一操作的改、写部分就被 Task B 抢占;③ Task B 更新 PORTA 后进入阻塞态;④ Task A 从被抢占处继续,修改寄存器中已保存的 PORTA 副本,再写回 PORTA。
此场景中 Task A 写回的是过期值:Task B 在 Task A 取走 PORTA 副本之后、Task A 把修改值写回寄存器之前修改了 PORTA;Task A 写回时覆盖了 Task B 已做的修改,实质上损坏了 PORTA 寄存器值。本例用外设寄存器,但对变量执行读-改-写操作时原理相同。
7.1.3变量的非原子访问
更新结构体多个成员,或更新大于架构自然字长的变量(例如 16 位机器上更新 32 位变量),都是非原子操作;若被打断,可能造成数据丢失或损坏。
7.1.4函数可重入性
若一个函数可安全地被多个任务调用、或同时被任务和中断调用,则称其“可重入”。可重入函数也称“线程安全”,因为可被多个执行线程访问而无数据或逻辑操作损坏风险。
每个任务维护自己的栈和自己的一组处理器(硬件)寄存器值。若函数除栈上数据或寄存器保存数据外不访问任何数据,则函数可重入、线程安全。清单 112 是可重入函数示例;清单 113 是不可重入函数示例。
/* A parameter is passed into the function. This will either be passed on the stack,
or in a processor register. Either way is safe as each task or interrupt that calls
the function maintains its own stack and its own set of register values, so each task
or interrupt that calls the function will have its own copy of lVar1. */
long lAddOneHundred( long lVar1 )
{
/* This function scope variable will also be allocated to the stack or a register,
depending on the compiler and optimization level. Each task or interrupt that calls
this function will have its own copy of lVar2. */
long lVar2;
lVar2 = lVar1 + 100;
return lVar2;
}/* In this case lVar1 is a global variable, so every task that calls
lNonsenseFunction will access the same single copy of the variable. */
long lVar1;
long lNonsenseFunction( void )
{
/* lState is static, so is not allocated on the stack. Each task that calls this
function will access the same single copy of the variable. */
static long lState = 0;
long lReturn;
switch( lState )
{
case 0 : lReturn = lVar1 + 10;
lState = 1;
break;
case 1 : lReturn = lVar1 + 20;
lState = 0;
break;
}
}7.1.5互斥
为始终保持数据一致性,对任务之间、或任务与中断之间共享资源的访问,必须用“互斥”技术管理。目标是:一旦任务开始访问不可重入、非线程安全的共享资源,同一任务就独占该资源,直到资源回到一致状态。
FreeRTOS 提供多种实现互斥的特性;但最佳互斥方法是(在可行时,尽管往往不实际)在设计应用时就让资源不被共享,每个资源只由单个任务访问。
7.1.6范围
本章帮助读者理解:何时以及为何需要资源管理与控制;什么是临界区;互斥的含义;挂起调度器的含义;如何使用互斥量;如何创建并使用守门人任务;什么是优先级反转,以及优先级继承如何降低(但不能消除)其影响。
7.2临界区与挂起调度器
7.2.1基本临界区
基本临界区是分别由 taskENTER_CRITICAL() 与 taskEXIT_CRITICAL() 宏调用包围的代码区域,临界区也称临界区域。两个宏不带参数、不返回值,用法见清单 114。
/* Ensure access to the PORTA register cannot be interrupted by placing it within a critical section. Enter the critical section. */ taskENTER_CRITICAL(); /* A switch to another task cannot occur between the call to taskENTER_CRITICAL() and the call to taskEXIT_CRITICAL(). Interrupts may still execute on FreeRTOS ports that allow interrupt nesting, but only interrupts whose logical priority is above the value assigned to the configMAX_SYSCALL_INTERRUPT_PRIORITY constant – and those interrupts are not permitted to call FreeRTOS API functions. */ PORTA |= 0x01; /* Access to PORTA has finished, so it is safe to exit the critical section. */ taskEXIT_CRITICAL();
本书配套示例工程用 vPrintString() 向标准输出写字符串(Windows 移植下即终端窗口)。它被许多不同任务调用,因此理论上其实现可用临界区保护对标准输出的访问,如清单 115。
void vPrintString( const char *pcString )
{
/* Write the string to stdout, using a critical section as a crude method of
mutual exclusion. */
taskENTER_CRITICAL();
{
printf( "%s", pcString );
fflush( stdout );
}
taskEXIT_CRITICAL();
}这样实现的临界区是非常粗糙的互斥手段:它通过关闭中断(完全关闭,或屏蔽到 configMAX_SYSCALL_INTERRUPT_PRIORITY 设定的中断优先级,取决于移植)来工作。抢占式上下文切换只能在中断内发生,因此只要中断保持关闭,调用 taskENTER_CRITICAL() 的任务保证一直留在运行态,直到退出临界区。
基本临界区必须保持很短,否则会负面影响中断响应时间。每次 taskENTER_CRITICAL() 都必须与一次 taskEXIT_CRITICAL() 紧密配对。因此不应像清单 115 那样用临界区保护标准输出(写终端可能是较长操作);本章示例将探讨替代方案。
临界区可以嵌套,因为内核记录嵌套深度;只有嵌套深度回到 0(即每次进入临界区都对应一次退出)时才真正退出临界区。
调用 taskENTER_CRITICAL() 与 taskEXIT_CRITICAL() 是任务改变处理器中断使能状态的唯一合法方式;用其他方式改变会使宏的嵌套计数失效。
两个宏不以“FromISR”结尾,绝不能从 ISR 调用。taskENTER_CRITICAL_FROM_ISR() 是 taskENTER_CRITICAL() 的中断安全版本,taskEXIT_CRITICAL_FROM_ISR() 是 taskEXIT_CRITICAL() 的中断安全版本;它们只在允许中断嵌套的移植上提供。
taskENTER_CRITICAL_FROM_ISR() 返回一个值,必须传入配对的 taskEXIT_CRITICAL_FROM_ISR() 调用,见清单 116。
void vAnInterruptServiceRoutine( void )
{
/* Declare a variable in which the return value from taskENTER_CRITICAL_FROM_ISR()
will be saved. */
UBaseType_t uxSavedInterruptStatus;
/* This part of the ISR can be interrupted by any higher priority interrupt. */
/* Use taskENTER_CRITICAL_FROM_ISR() to protect a region of this ISR. Save the
value returned from taskENTER_CRITICAL_FROM_ISR() so it can be passed into the
matching call to taskEXIT_CRITICAL_FROM_ISR(). */
uxSavedInterruptStatus = taskENTER_CRITICAL_FROM_ISR();
/* This part of the ISR is between the call to taskENTER_CRITICAL_FROM_ISR() and
taskEXIT_CRITICAL_FROM_ISR(), so can only be interrupted by interrupts that have
a priority above that set by the configMAX_SYSCALL_INTERRUPT_PRIORITY constant. */
/* Exit the critical section again by calling taskEXIT_CRITICAL_FROM_ISR(),
passing in the value returned by the matching call to
taskENTER_CRITICAL_FROM_ISR(). */
taskEXIT_CRITICAL_FROM_ISR( uxSavedInterruptStatus );
/* This part of the ISR can be interrupted by any higher priority interrupt. */
}若进入、退出临界区所执行代码的处理时间,比临界区实际保护的代码还多,就是浪费。基本临界区进入快、退出快、始终确定,适合保护非常短的代码区域。
7.2.2挂起(锁定)调度器
临界区也可通过挂起调度器创建;挂起调度器也称“锁定”调度器。基本临界区保护代码区域不被其他任务和中断访问;通过挂起调度器实现的临界区只保护代码区域不被其他任务访问,因为中断保持使能。
对于长到无法靠简单关中断实现的临界区,可改为挂起调度器。但调度器挂起期间的中断活动可能使恢复(解除挂起)调度器成为较长操作,因此每种情况都要权衡最佳方法。
7.2.3vTaskSuspendAll() API 函数
void vTaskSuspendAll( void );
调用 vTaskSuspendAll() 挂起调度器。挂起调度器阻止上下文切换发生,但中断保持使能。若调度器挂起期间中断请求上下文切换,该请求被保持为挂起状态,只在调度器恢复(解除挂起)时执行。调度器挂起期间不得调用 FreeRTOS API 函数。
7.2.4xTaskResumeAll() API 函数
BaseType_t xTaskResumeAll( void );
调用 xTaskResumeAll() 恢复(解除挂起)调度器。
| 返回值 | 说明 |
|---|---|
| 返回值 | 调度器挂起期间请求的上下文切换被保持为挂起状态,只在调度器恢复时执行。若在 xTaskResumeAll() 返回前执行了挂起的上下文切换,返回 pdTRUE;否则返回 pdFALSE。 |
vTaskSuspendAll() 与 xTaskResumeAll() 调用可以嵌套,内核记录嵌套深度;只有深度回到 0(每次挂起都对应一次恢复)才真正恢复调度器。
清单 119 给出 vPrintString() 的实际实现:挂起调度器以保护对终端输出的访问。
void vPrintString( const char *pcString )
{
/* Write the string to stdout, suspending the scheduler as a method of mutual
exclusion. */
vTaskSuspendScheduler();
{
printf( "%s", pcString );
fflush( stdout );
}
xTaskResumeScheduler();
}7.3互斥量(与二值信号量)
互斥量(Mutex)是一种特殊的二值信号量,用于控制对两个或多个任务共享资源的访问。MUTEX 一词源自“MUTual EXclusion(互斥)”。要使用互斥量,必须在 FreeRTOSConfig.h 中把 configUSE_MUTEXES 设为 1。
在互斥场景中,互斥量可看作与被共享资源关联的令牌:任务要合法访问资源,必须先成功“取得”令牌(成为令牌持有者);令牌持有者用完资源后必须把令牌“归还”。令牌归还后,其他任务才能成功取得令牌并安全访问同一共享资源;未持有令牌的任务不允许访问共享资源。该机制见图 63。
尽管互斥量与二值信号量有许多共同特征,图 63(互斥量用于互斥)场景与图 53(二值信号量用于同步)场景完全不同。根本区别在于信号量取得之后如何处理:
- 用于互斥的信号量必须始终归还;
- 用于同步的信号量通常被丢弃、不再归还。
该机制完全依赖应用编写者的纪律:任务在任何时候都“可以”访问资源,但每个任务“约定”除非能成为互斥量持有者否则不访问。
7.3.1xSemaphoreCreateMutex() API 函数
FreeRTOS V9.0.0 还提供 xSemaphoreCreateMutexStatic(),在编译期静态分配创建互斥量所需内存。互斥量是信号量的一种;各种 FreeRTOS 信号量的句柄都存于 SemaphoreHandle_t 类型变量。使用前必须先创建;创建互斥量类型信号量用 xSemaphoreCreateMutex()。
SemaphoreHandle_t xSemaphoreCreateMutex( void );
| 参数名 / 返回值 | 说明 |
|---|---|
| 返回值 | 返回 NULL 表示堆内存不足,FreeRTOS 无法分配互斥量数据结构(堆管理见第 2 章);返回非 NULL 表示互斥量创建成功,返回值应保存为所创建互斥量的句柄。 |
7.3.2示例 20:改用信号量重写 vPrintString()
本例创建 vPrintString() 的新版本 prvNewPrintString(),再由多个任务调用。prvNewPrintString() 功能与 vPrintString() 相同,但用互斥量而非锁定调度器来控制对标准输出的访问,实现见清单 121。
static void prvNewPrintString( const char *pcString )
{
/* The mutex is created before the scheduler is started, so already exists by the
time this task executes.
Attempt to take the mutex, blocking indefinitely to wait for the mutex if it is
not available straight away. The call to xSemaphoreTake() will only return when
the mutex has been successfully obtained, so there is no need to check the
function return value. If any other delay period was used then the code must
check that xSemaphoreTake() returns pdTRUE before accessing the shared resource
(which in this case is standard out). As noted earlier in this book, indefinite
time outs are not recommended for production code. */
xSemaphoreTake( xMutex, portMAX_DELAY );
{
/* The following line will only execute once the mutex has been successfully
obtained. Standard out can be accessed freely now as only one task can have
the mutex at any one time. */
printf( "%s", pcString );
fflush( stdout );
/* The mutex MUST be given back! */
}
xSemaphoreGive( xMutex );
}prvNewPrintString() 由 prvPrintTask() 实现的两个任务实例反复调用,每次调用之间使用伪随机延时;任务参数用于向每个任务实例传入唯一字符串。prvPrintTask() 实现见清单 122。
static void prvPrintTask( void *pvParameters )
{
char *pcStringToPrint;
const TickType_t xMaxBlockTimeTicks = 0x20;
/* Two instances of this task are created. The string printed by the task is
passed into the task using the task’s parameter. The parameter is cast to the
required type. */
pcStringToPrint = ( char * ) pvParameters;
for( ;; )
{
/* Print out the string using the newly defined function. */
prvNewPrintString( pcStringToPrint );
/* Wait a pseudo random time. Note that rand() is not necessarily reentrant,
but in this case it does not really matter as the code does not care what
value is returned. In a more secure application a version of rand() that is
known to be reentrant should be used - or calls to rand() should be protected
using a critical section. */
vTaskDelay( ( rand() % xMaxBlockTimeTicks ) );
}
}与通常一样,main() 先创建互斥量、创建任务,再启动调度器,实现见清单 123。两个 prvPrintTask() 实例以不同优先级创建,低优先级任务有时会被高优先级任务抢占。由于用互斥量保证每个任务独占访问终端,即使发生抢占,显示的字符串也正确、不会损坏。降低任务在阻塞态的最大时间(由 xMaxBlockTimeTicks 常量设定)可提高抢占频率。
示例 20 在 FreeRTOS Windows 移植上使用时的注意事项:调用 printf() 会产生 Windows 系统调用;系统调用不在 FreeRTOS 控制之内,可能引入不稳定。Windows 系统调用的执行方式意味着即使不使用互斥量,也很少看到损坏字符串。
int main( void )
{
/* Before a semaphore is used it must be explicitly created. In this example a
mutex type semaphore is created. */
xMutex = xSemaphoreCreateMutex();
/* Check the semaphore was created successfully before creating the tasks. */
if( xMutex != NULL )
{
/* Create two instances of the tasks that write to stdout. The string they
write is passed in to the task as the task’s parameter. The tasks are
created at different priorities so some pre-emption will occur. */
xTaskCreate( prvPrintTask, "Print1", 1000,
"Task 1 ***************************************\r\n", 1, NULL );
xTaskCreate( prvPrintTask, "Print2", 1000,
"Task 2 ---------------------------------------\r\n", 2, NULL );
/* Start the scheduler so the created tasks start executing. */
vTaskStartScheduler();
}
/* If all is well then main() will never reach here as the scheduler will now be
running the tasks. If main() does reach here then it is likely that there was
insufficient heap memory available for the idle task to be created. Chapter 2
provides more information on heap memory management. */
for( ;; );
}
图 64 表明:正如预期,终端显示的字符串没有损坏;随机排列是任务使用随机延时的结果。可能执行序列见图 65。
7.3.3优先级反转
图 65 演示了用互斥量提供互斥的一个潜在陷阱:高优先级 Task 2 不得不等待低优先级 Task 1 放弃互斥量控制权。高优先级任务以这种方式被低优先级任务延迟,称为“优先级反转”。若高优先级任务等待信号量期间又有一个中等优先级任务开始执行,这种不良行为会进一步放大:结果是高优先级任务等待低优先级任务——而低优先级任务甚至无法执行。最坏情况见图 66。
优先级反转可能是严重问题,但在小型嵌入式系统中,往往可在系统设计阶段通过考虑资源访问方式加以避免。
7.3.4优先级继承
FreeRTOS 互斥量与二值信号量非常相似,区别在于互斥量包含基本“优先级继承”机制,二值信号量没有。优先级继承是一种把优先级反转负面影响降到最小的方案;它并不“修复”优先级反转,只是通过确保反转始终有时间上界来减轻其影响。不过优先级继承会使系统时序分析复杂化,不应依赖它保证系统正确运行。
优先级继承的工作方式:把互斥量持有者的优先级临时提升到尝试取得同一互斥量的最高优先级任务的优先级。持有互斥量的低优先级任务“继承”等待互斥量任务的优先级,见图 67。互斥量持有者归还互斥量时,其优先级自动恢复为原值。
如前所述,优先级继承功能会影响使用互斥量任务的优先级;因此互斥量绝不能在中断服务程序中使用。
7.3.5死锁(致命拥抱)
“死锁”是用互斥量实现互斥的另一个潜在陷阱,有时也称更戏剧化的名字“致命拥抱”。死锁发生在两个任务因互相等待对方持有的资源而都无法继续时。设想 Task A 与 Task B 都需要取得互斥量 X 和互斥量 Y 才能执行某动作:① Task A 执行并成功取得互斥量 X;② Task A 被 Task B 抢占;③ Task B 成功取得互斥量 Y,再尝试取得互斥量 X,但 X 由 Task A 持有、对 Task B 不可用;Task B 选择进入阻塞态等待 X 释放;④ Task A 继续执行,尝试取得互斥量 Y,但 Y 由 Task B 持有、对 Task A 不可用;Task A 选择进入阻塞态等待 Y 释放。
场景结束时:Task A 等待 Task B 持有的互斥量,Task B 等待 Task A 持有的互斥量;两个任务都无法继续,死锁发生。
与优先级反转一样,避免死锁的最佳方法是在设计阶段考虑其可能性,并设计系统确保死锁不会发生。特别地(本书前文已述),任务无限期(无超时)等待取得互斥量通常是不良做法;应使用比预期最大等待时间略长的超时,未能在该时间内取得互斥量即视为设计错误的征兆,可能就是死锁。实际中,死锁在小型嵌入式系统中不是大问题,因为设计者可全面了解整个应用,从而识别并消除可能发生死锁的区域。
7.3.6递归互斥量
任务也可能与自身死锁:任务在未先归还互斥量的情况下多次尝试取得同一互斥量时就会发生。设想:① 任务成功取得互斥量;② 持有互斥量期间,任务调用某个库函数;③ 库函数实现尝试取得同一互斥量,进入阻塞态等待互斥量可用。场景结束时任务在阻塞态等待互斥量归还,但任务本身已是持有者;任务在等待自己,死锁发生。
这类死锁可用递归互斥量代替标准互斥量避免。递归互斥量可被同一任务多次“取得”;只有每次“取得”递归互斥量都对应一次“归还”调用后,递归互斥量才真正归还。标准互斥量与递归互斥量的创建和使用方式类似:
- 标准互斥量用
xSemaphoreCreateMutex()创建;递归互斥量用xSemaphoreCreateRecursiveMutex()创建,两个 API 原型相同。 - 标准互斥量用
xSemaphoreTake()“取得”;递归互斥量用xSemaphoreTakeRecursive()“取得”,两个 API 原型相同。 - 标准互斥量用
xSemaphoreGive()“归还”;递归互斥量用xSemaphoreGiveRecursive()“归还”,两个 API 原型相同。
清单 124 演示如何创建并使用递归互斥量。
/* Recursive mutexes are variables of type SemaphoreHandle_t. */
SemaphoreHandle_t xRecursiveMutex;
/* The implementation of a task that creates and uses a recursive mutex. */
void vTaskFunction( void *pvParameters )
{
const TickType_t xMaxBlock20ms = pdMS_TO_TICKS( 20 );
/* Before a recursive mutex is used it must be explicitly created. */
xRecursiveMutex = xSemaphoreCreateRecursiveMutex();
/* Check the semaphore was created successfully. configASSERT() is described in
section 11.2. */
configASSERT( xRecursiveMutex );
/* As per most tasks, this task is implemented as an infinite loop. */
for( ;; )
{
/* ... */
/* Take the recursive mutex. */
if( xSemaphoreTakeRecursive( xRecursiveMutex, xMaxBlock20ms ) == pdPASS )
{
/* The recursive mutex was successfully obtained. The task can now access
the resource the mutex is protecting. At this point the recursive call
count (which is the number of nested calls to xSemaphoreTakeRecursive())
is 1, as the recursive mutex has only been taken once. */
/* While it already holds the recursive mutex, the task takes the mutex
again. In a real application, this is only likely to occur inside a sub-
function called by this task, as there is no practical reason to knowingly
take the same mutex more than once. The calling task is already the mutex
holder, so the second call to xSemaphoreTakeRecursive() does nothing more
than increment the recursive call count to 2. */
xSemaphoreTakeRecursive( xRecursiveMutex, xMaxBlock20ms );
/* ... */
/* The task returns the mutex after it has finished accessing the resource
the mutex is protecting. At this point the recursive call count is 2, so
the first call to xSemaphoreGiveRecursive() does not return the mutex.
Instead, it simply decrements the recursive call count back to 1. */
xSemaphoreGiveRecursive( xRecursiveMutex );
/* The next call to xSemaphoreGiveRecursive() decrements the recursive call
count to 0, so this time the recursive mutex is returned.*/
xSemaphoreGiveRecursive( xRecursiveMutex );
/* Now one call to xSemaphoreGiveRecursive() has been executed for every
proceeding call to xSemaphoreTakeRecursive(), so the task is no longer the
mutex holder.
}
}
}7.3.7互斥量与任务调度
若两个不同优先级任务使用同一互斥量,FreeRTOS 调度策略使任务执行顺序明确:选择能够运行的最高优先级任务进入运行态。例如高优先级任务在阻塞态等待低优先级任务持有的互斥量,则低优先级任务一归还互斥量,高优先级任务就抢占它并成为持有者;该场景已在图 67 见过。
但任务优先级相同时,人们常对执行顺序做出错误假设。若 Task 1 与 Task 2 优先级相同,Task 1 在阻塞态等待 Task 2 持有的互斥量,则 Task 2“归还”互斥量时 Task 1 不会抢占 Task 2;Task 2 仍留在运行态,Task 1 只是从阻塞态移到就绪态。该场景见图 68,竖线标记节拍中断发生时刻。
图 68 场景中,互斥量可用后 FreeRTOS 调度器没有立即让 Task 1 成为运行态任务,原因:① Task 1 与 Task 2 优先级相同,除非 Task 2 进入阻塞态,否则切换到 Task 1 不应发生,要等到下一次节拍中断(假定 FreeRTOSConfig.h 中 configUSE_TIME_SLICING 设为 1);② 若任务在紧凑循环中使用互斥量,且每次“归还”互斥量都发生上下文切换,任务在运行态停留时间会很短;两个或更多任务在紧凑循环中使用同一互斥量时,处理时间会被任务间快速切换浪费。
若多个任务在紧凑循环中使用互斥量、且使用互斥量的任务优先级相同,必须注意确保各任务获得大致均等的处理时间。任务可能获得不均等处理时间的原因见图 69:它展示清单 125 所示任务的两个实例以相同优先级创建时可能出现的执行序列。
/* The implementation of a task that uses a mutex in a tight loop. The task creates
a text string in a local buffer, then writes the string to a display. Access to the
display is protected by a mutex. */
void vATask( void *pvParameter )
{
extern SemaphoreHandle_t xMutex;
char cTextBuffer[ 128 ];
for( ;; )
{
/* Generate the text string – this is a fast operation. */
vGenerateTextInALocalBuffer( cTextBuffer );
/* Obtain the mutex that is protecting access to the display. */
xSemaphoreTake( xMutex, portMAX_DELAY );
/* Write the generated text to the display – this is a slow operation. */
vCopyTextToFrameBuffer( cTextBuffer );
/* The text has been written to the display, so return the mutex. */
xSemaphoreGive( xMutex );
}
}清单 125 注释指出:生成字符串是快操作,更新显示是慢操作。因此更新显示期间持有互斥量,任务大部分运行时间都持有互斥量。
图 69 步骤 7 显示 Task 1 重新进入阻塞态——该动作发生在 xSemaphoreTake() API 函数内部。图 69 表明:Task 1 要取得互斥量,必须等到某时间片起点恰好落在 Task 2 不是持有者的短暂时段之一。
图 69 场景可在 xSemaphoreGive() 调用之后加一次 taskYIELD() 调用来避免,见清单 126:若任务持有互斥量期间节拍计数发生了变化,则调用 taskYIELD()。
void vFunction( void *pvParameter )
{
extern SemaphoreHandle_t xMutex;
char cTextBuffer[ 128 ];
TickType_t xTimeAtWhichMutexWasTaken;
for( ;; )
{
/* Generate the text string – this is a fast operation. */
vGenerateTextInALocalBuffer( cTextBuffer );
/* Obtain the mutex that is protecting access to the display. */
xSemaphoreTake( xMutex, portMAX_DELAY );
/* Record the time at which the mutex was taken. */
xTimeAtWhichMutexWasTaken = xTaskGetTickCount();
/* Write the generated text to the display – this is a slow operation. */
vCopyTextToFrameBuffer( cTextBuffer );
/* The text has been written to the display, so return the mutex. */
xSemaphoreGive( xMutex );
/* If taskYIELD() was called on each iteration then this task would only ever
remain in the Running state for a short period of time, and processing time
would be wasted by rapidly switching between tasks. Therefore, only call
taskYIELD() if the tick count changed while the mutex was held. */
if( xTaskGetTickCount() != xTimeAtWhichMutexWasTaken )
{
taskYIELD();
}
}
}7.4闸门任务(守门人任务)
闸门任务提供一种干净的互斥实现方法,没有优先级反转或死锁风险。闸门任务是独占某资源的任务:只有闸门任务被允许直接访问该资源;任何其他需要访问资源的任务,只能间接借助闸门的服务访问。
7.4.1示例 21:改用闸门任务重写 vPrintString()
示例 21 给出 vPrintString() 的另一种替代实现:本次用闸门任务管理对标准输出的访问。任务想向标准输出写消息时,不直接调用打印函数,而是把消息发给闸门任务。
闸门任务用 FreeRTOS 队列串行化对标准输出的访问;任务内部实现不必考虑互斥,因为它是唯一被允许直接访问标准输出的任务。闸门任务大部分时间在阻塞态等待队列上消息到达;消息到达后,闸门只负责把消息写到标准输出,再回到阻塞态等待下一条消息,实现见清单 128。
中断可以向队列发送,因此中断服务程序也能安全地借助闸门服务向终端写消息。本例用节拍钩子函数每 200 拍写出一条消息。
节拍钩子(或称节拍回调)是内核在每次节拍中断中调用的函数。使用节拍钩子:① 在 FreeRTOSConfig.h 中把 configUSE_TICK_HOOK 设为 1;② 按清单 127 给出的确切函数名和原型提供钩子实现。
void vApplicationTickHook( void );
节拍钩子函数在节拍中断上下文内执行,因此必须保持极短、只使用适度栈空间,且不得调用任何不以“FromISR()”结尾的 FreeRTOS API 函数。调度器总是在节拍钩子函数之后立即执行,因此从节拍钩子调用的中断安全 FreeRTOS API 不必使用 pxHigherPriorityTaskWoken 参数,该参数可置为 NULL。
static void prvStdioGatekeeperTask( void *pvParameters )
{
char *pcMessageToPrint;
/* This is the only task that is allowed to write to standard out. Any other
task wanting to write a string to the output does not access standard out
directly, but instead sends the string to this task. As only this task accesses
standard out there are no mutual exclusion or serialization issues to consider
within the implementation of the task itself. */
for( ;; )
{
/* Wait for a message to arrive. An indefinite block time is specified so
there is no need to check the return value – the function will only return
when a message has been successfully received. */
xQueueReceive( xPrintQueue, &pcMessageToPrint, portMAX_DELAY );
/* Output the received string. */
printf( "%s", pcMessageToPrint );
fflush( stdout );
/* Loop back to wait for the next message. */
}
}向队列写消息的任务见清单 129。与前面一样创建任务的两个独立实例,任务写入队列的字符串通过任务参数传入。
static void prvPrintTask( void *pvParameters )
{
int iIndexToString;
const TickType_t xMaxBlockTimeTicks = 0x20;
/* Two instances of this task are created. The task parameter is used to pass
an index into an array of strings into the task. Cast this to the required
type. */
iIndexToString = ( int ) pvParameters;
for( ;; )
{
/* Print out the string, not directly, but instead by passing a pointer to
the string to the gatekeeper task via a queue. The queue is created before
the scheduler is started so will already exist by the time this task executes
for the first time. A block time is not specified because there should
always be space in the queue. */
xQueueSendToBack( xPrintQueue, &( pcStringsToPrint[ iIndexToString ] ), 0 );
/* Wait a pseudo random time. Note that rand() is not necessarily reentrant,
but in this case it does not really matter as the code does not care what
value is returned. In a more secure application a version of rand() that is
known to be reentrant should be used - or calls to rand() should be protected
using a critical section. */
vTaskDelay( ( rand() % xMaxBlockTimeTicks ) );
}
}节拍钩子函数统计被调用次数,计数到达 200 时把消息发给闸门任务。仅作演示:节拍钩子写到队列前端,任务写到队列后端,实现见清单 130。
void vApplicationTickHook( void )
{
static int iCount = 0;
/* Print out a message every 200 ticks. The message is not written out directly,
but sent to the gatekeeper task. */
iCount++;
if( iCount >= 200 )
{
/* As xQueueSendToFrontFromISR() is being called from the tick hook, it is
not necessary to use the xHigherPriorityTaskWoken parameter (the third
parameter), and the parameter is set to NULL. */
xQueueSendToFrontFromISR( xPrintQueue,
&( pcStringsToPrint[ 2 ] ),
NULL );
/* Reset the count ready to print out the string again in 200 ticks time. */
iCount = 0;
}
}与通常一样,main() 创建运行示例所需的队列和任务,再启动调度器,实现见清单 131。
/* Define the strings that the tasks and interrupt will print out via the
gatekeeper. */
static char *pcStringsToPrint[] =
{
"Task 1 ****************************************************\r\n",
"Task 2 ----------------------------------------------------\r\n",
"Message printed from the tick hook interrupt ##############\r\n"
};
/*-----------------------------------------------------------*/
/* Declare a variable of type QueueHandle_t. The queue is used to send messages
from the print tasks and the tick interrupt to the gatekeeper task. */
QueueHandle_t xPrintQueue;
/*-----------------------------------------------------------*/
int main( void )
{
/* Before a queue is used it must be explicitly created. The queue is created
to hold a maximum of 5 character pointers. */
xPrintQueue = xQueueCreate( 5, sizeof( char * ) );
/* Check the queue was created successfully. */
if( xPrintQueue != NULL )
{
/* Create two instances of the tasks that send messages to the gatekeeper.
The index to the string the task uses is passed to the task via the task
parameter (the 4th parameter to xTaskCreate()). The tasks are created at
different priorities so the higher priority task will occasionally preempt
the lower priority task. */
xTaskCreate( prvPrintTask, "Print1", 1000, ( void * ) 0, 1, NULL );
xTaskCreate( prvPrintTask, "Print2", 1000, ( void * ) 1, 2, NULL );
/* Create the gatekeeper task. This is the only task that is permitted
to directly access standard out. */
xTaskCreate( prvStdioGatekeeperTask, "Gatekeeper", 1000, NULL, 0, NULL );
/* Start the scheduler so the created tasks start executing. */
vTaskStartScheduler();
}
/* If all is well then main() will never reach here as the scheduler will now be
running the tasks. If main() does reach here then it is likely that there was
insufficient heap memory available for the idle task to be created. Chapter 2
provides more information on heap memory management. */
for( ;; );
}执行示例 21 产生的输出见图 70。可见,来自任务的字符串与来自中断的字符串都正确打印,没有损坏。

闸门任务被分配比打印任务更低的优先级——发给闸门的消息留在队列中,直到两个打印任务都进入阻塞态。某些场景下给闸门更高优先级是合适的,消息可立即处理;但这样做的代价是:在闸门完成访问受保护资源之前,会拖延低优先级任务。