Mastering the FreeRTOS Real Time Kernel · 中文版 /7 资源管理

7 · 原书 260–291 页资源管理

Resource Management

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
清单 111 · 读-改-写序列示例

这是“非原子”操作,因为完成它需要多条指令、可被打断。设想两个任务尝试更新内存映射寄存器 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;
}
清单 112 · 可重入函数示例
/* 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;
    }
}
清单 113 · 不可重入函数示例

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();
清单 114 · 用临界区保护对寄存器的访问

本书配套示例工程用 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();
}
清单 115 · vPrintString() 的一种可能实现

这样实现的临界区是非常粗糙的互斥手段:它通过关闭中断(完全关闭,或屏蔽到 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. */
}
清单 116 · 在中断服务程序中使用临界区

若进入、退出临界区所执行代码的处理时间,比临界区实际保护的代码还多,就是浪费。基本临界区进入快、退出快、始终确定,适合保护非常短的代码区域。

7.2.2挂起(锁定)调度器

临界区也可通过挂起调度器创建;挂起调度器也称“锁定”调度器。基本临界区保护代码区域不被其他任务和中断访问;通过挂起调度器实现的临界区只保护代码区域不被其他任务访问,因为中断保持使能。

对于长到无法靠简单关中断实现的临界区,可改为挂起调度器。但调度器挂起期间的中断活动可能使恢复(解除挂起)调度器成为较长操作,因此每种情况都要权衡最佳方法。

7.2.3vTaskSuspendAll() API 函数

void vTaskSuspendAll( void );
清单 117 · vTaskSuspendAll() API 原型

调用 vTaskSuspendAll() 挂起调度器。挂起调度器阻止上下文切换发生,但中断保持使能。若调度器挂起期间中断请求上下文切换,该请求被保持为挂起状态,只在调度器恢复(解除挂起)时执行。调度器挂起期间不得调用 FreeRTOS API 函数。

7.2.4xTaskResumeAll() API 函数

BaseType_t xTaskResumeAll( void );
清单 118 · xTaskResumeAll() API 原型

调用 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();
}
清单 119 · vPrintString() 的实现

7.3互斥量(与二值信号量)

互斥量(Mutex)是一种特殊的二值信号量,用于控制对两个或多个任务共享资源的访问。MUTEX 一词源自“MUTual EXclusion(互斥)”。要使用互斥量,必须在 FreeRTOSConfig.h 中把 configUSE_MUTEXES 设为 1。

在互斥场景中,互斥量可看作与被共享资源关联的令牌:任务要合法访问资源,必须先成功“取得”令牌(成为令牌持有者);令牌持有者用完资源后必须把令牌“归还”。令牌归还后,其他任务才能成功取得令牌并安全访问同一共享资源;未持有令牌的任务不允许访问共享资源。该机制见图 63。

尽管互斥量与二值信号量有许多共同特征,图 63(互斥量用于互斥)场景与图 53(二值信号量用于同步)场景完全不同。根本区别在于信号量取得之后如何处理:

图 63(用互斥量实现互斥):① 两个任务都想访问资源,但只有互斥量(令牌)持有者才被允许访问;② Task A 尝试取得互斥量,互斥量可用,Task A 成功成为持有者,被允许访问资源;③ Task B 执行并尝试取得同一互斥量,互斥量仍由 Task A 持有,尝试失败,Task B 不被允许访问受保护资源;④ Task B 选择进入阻塞态等待互斥量,让 Task A 再次运行;Task A 用完资源后“归还”互斥量;⑤ Task A 归还互斥量使 Task B 退出阻塞态(互斥量现已可用),Task B 成功取得互斥量,被允许访问资源;⑥ Task B 用完资源后也归还互斥量,互斥量再次对两个任务可用。

该机制完全依赖应用编写者的纪律:任务在任何时候都“可以”访问资源,但每个任务“约定”除非能成为互斥量持有者否则不访问。

7.3.1xSemaphoreCreateMutex() API 函数

FreeRTOS V9.0.0 还提供 xSemaphoreCreateMutexStatic(),在编译期静态分配创建互斥量所需内存。互斥量是信号量的一种;各种 FreeRTOS 信号量的句柄都存于 SemaphoreHandle_t 类型变量。使用前必须先创建;创建互斥量类型信号量用 xSemaphoreCreateMutex()。

SemaphoreHandle_t xSemaphoreCreateMutex( void );
清单 120 · xSemaphoreCreateMutex() API 原型
参数名 / 返回值说明
返回值返回 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 );
}
清单 121 · prvNewPrintString() 的实现

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 ) );
    }
}
清单 122 · 示例 20 的 prvPrintTask() 实现

与通常一样,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( ;; );
}
清单 123 · 示例 20 的 main() 实现
图 64 · 执行示例 20 时产生的输出
图 64 · 执行示例 20 时产生的输出

图 64 表明:正如预期,终端显示的字符串没有损坏;随机排列是任务使用随机延时的结果。可能执行序列见图 65。

图 65(示例 20 可能执行序列):① Task 1 延时到期,抢占空闲任务;② Task 1 取得互斥量并开始写字符串;整条字符串尚未输出完,Task 1 被更高优先级 Task 2 抢占;③ Task 2 尝试取得互斥量,但互斥量仍由 Task 1 持有,Task 2 进入阻塞态,Task 1 得以再次执行;④ Task 1 写完字符串并归还互斥量,Task 2 退出阻塞态,再次抢占 Task 1;⑤ Task 2 写出字符串、归还信号量,再进入阻塞态等待下一次执行;Task 1 得以运行,随后也进入阻塞态等待下一次执行,只剩空闲任务可运行。

7.3.3优先级反转

图 65 演示了用互斥量提供互斥的一个潜在陷阱:高优先级 Task 2 不得不等待低优先级 Task 1 放弃互斥量控制权。高优先级任务以这种方式被低优先级任务延迟,称为“优先级反转”。若高优先级任务等待信号量期间又有一个中等优先级任务开始执行,这种不良行为会进一步放大:结果是高优先级任务等待低优先级任务——而低优先级任务甚至无法执行。最坏情况见图 66。

图 66(最坏情况优先级反转场景):① LP(低优先级)任务取得互斥量,随后被 HP(高优先级)任务抢占;② HP 任务尝试取得互斥量,因仍由 LP 任务持有而失败,进入阻塞态等待互斥量可用;③ LP 任务继续执行,但在归还互斥量前被 MP(中等优先级)任务抢占;④ MP 任务正在运行;HP 任务仍在等待 LP 任务归还互斥量,但 LP 任务甚至没有在执行。

优先级反转可能是严重问题,但在小型嵌入式系统中,往往可在系统设计阶段通过考虑资源访问方式加以避免。

7.3.4优先级继承

FreeRTOS 互斥量与二值信号量非常相似,区别在于互斥量包含基本“优先级继承”机制,二值信号量没有。优先级继承是一种把优先级反转负面影响降到最小的方案;它并不“修复”优先级反转,只是通过确保反转始终有时间上界来减轻其影响。不过优先级继承会使系统时序分析复杂化,不应依赖它保证系统正确运行。

优先级继承的工作方式:把互斥量持有者的优先级临时提升到尝试取得同一互斥量的最高优先级任务的优先级。持有互斥量的低优先级任务“继承”等待互斥量任务的优先级,见图 67。互斥量持有者归还互斥量时,其优先级自动恢复为原值。

图 67(优先级继承减轻优先级反转影响):① LP 任务取得互斥量后被 HP 任务抢占;② HP 任务尝试取得互斥量失败,进入阻塞态等待;③ LP 任务阻碍 HP 任务执行,因此继承 HP 任务优先级;LP 任务现在不会被 MP 任务抢占,优先级反转持续时间被降到最小;LP 任务归还互斥量后恢复原优先级;④ LP 任务归还互斥量使 HP 任务作为持有者退出阻塞态;HP 任务用完互斥量后归还;MP 任务只在 HP 任务回到阻塞态时才执行,因此 MP 任务绝不会阻碍 HP 任务。

如前所述,优先级继承功能会影响使用互斥量任务的优先级;因此互斥量绝不能在中断服务程序中使用。

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递归互斥量

任务也可能与自身死锁:任务在未先归还互斥量的情况下多次尝试取得同一互斥量时就会发生。设想:① 任务成功取得互斥量;② 持有互斥量期间,任务调用某个库函数;③ 库函数实现尝试取得同一互斥量,进入阻塞态等待互斥量可用。场景结束时任务在阻塞态等待互斥量归还,但任务本身已是持有者;任务在等待自己,死锁发生。

这类死锁可用递归互斥量代替标准互斥量避免。递归互斥量可被同一任务多次“取得”;只有每次“取得”递归互斥量都对应一次“归还”调用后,递归互斥量才真正归还。标准互斥量与递归互斥量的创建和使用方式类似:

清单 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.
       }
   }
}
清单 124 · 创建并使用递归互斥量

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(同优先级任务使用同一互斥量时的可能执行序列):① Task 2 执行一个时间片,期间“取得”互斥量;② 下一时间片开始时 Task 1 开始执行;③ Task 1 尝试取得 Task 2 持有的互斥量,进入阻塞态等待互斥量可用;④ Task 2 执行完剩余时间片,因 Task 1 被阻塞,继续留在运行态进入下一时间片;⑤ Task 2“归还”互斥量,解除 Task 1 阻塞;⑥ Task 1 直到下一时间片开始才重新进入运行态。

图 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 · 在紧凑循环中使用互斥量的任务

清单 125 注释指出:生成字符串是快操作,更新显示是慢操作。因此更新显示期间持有互斥量,任务大部分运行时间都持有互斥量。

图 69(清单 125 两个实例同优先级创建时可能的执行序列,竖线为节拍中断时刻):① Task 2 执行一个时间片,期间取得互斥量;② 下一时间片开始 Task 1 开始执行;③ Task 1 尝试取得 Task 2 持有的互斥量,进入阻塞态;④ Task 2 执行完剩余时间片,因 Task 1 阻塞而继续运行进入下一时间片;⑤ Task 2 归还互斥量,解除 Task 1 阻塞;⑥ Task 2 再次“取得”互斥量;⑦ 下一时间片开始 Task 1 执行,尝试取得 Task 2 持有的互斥量,再次进入阻塞态等待。

图 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();
        }
    }
}
清单 126 · 让循环中使用互斥量的任务获得更均等的处理时间,同时避免任务间切换过快浪费处理时间

7.4闸门任务(守门人任务)

闸门任务提供一种干净的互斥实现方法,没有优先级反转或死锁风险。闸门任务是独占某资源的任务:只有闸门任务被允许直接访问该资源;任何其他需要访问资源的任务,只能间接借助闸门的服务访问。

7.4.1示例 21:改用闸门任务重写 vPrintString()

示例 21 给出 vPrintString() 的另一种替代实现:本次用闸门任务管理对标准输出的访问。任务想向标准输出写消息时,不直接调用打印函数,而是把消息发给闸门任务。

闸门任务用 FreeRTOS 队列串行化对标准输出的访问;任务内部实现不必考虑互斥,因为它是唯一被允许直接访问标准输出的任务。闸门任务大部分时间在阻塞态等待队列上消息到达;消息到达后,闸门只负责把消息写到标准输出,再回到阻塞态等待下一条消息,实现见清单 128。

中断可以向队列发送,因此中断服务程序也能安全地借助闸门服务向终端写消息。本例用节拍钩子函数每 200 拍写出一条消息。

节拍钩子(或称节拍回调)是内核在每次节拍中断中调用的函数。使用节拍钩子:① 在 FreeRTOSConfig.h 中把 configUSE_TICK_HOOK 设为 1;② 按清单 127 给出的确切函数名和原型提供钩子实现。

    void vApplicationTickHook( void );
清单 127 · 节拍钩子函数的名称与原型

节拍钩子函数在节拍中断上下文内执行,因此必须保持极短、只使用适度栈空间,且不得调用任何不以“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. */
    }
}
清单 128 · 闸门任务

向队列写消息的任务见清单 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 ) );
    }
}
清单 129 · 示例 21 的打印任务实现

节拍钩子函数统计被调用次数,计数到达 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;
    }
}
清单 130 · 节拍钩子实现

与通常一样,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( ;; );
}
清单 131 · 示例 21 的 main() 实现

执行示例 21 产生的输出见图 70。可见,来自任务的字符串与来自中断的字符串都正确打印,没有损坏。

图 70 · 执行示例 21 时产生的输出
图 70 · 执行示例 21 时产生的输出

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