1. 程式人生 > >FreeRTOS 任務與排程器(2)

FreeRTOS 任務與排程器(2)

 在上一篇我們介紹了FreeRTOS任務的一些基本操作和功能,今天我們會介紹一個很好很強大的功能——任務通知

任務通知可以在不同任務之間傳遞資訊,它可以取代二值訊號量、計數訊號量、事件標誌組、深度為1的訊息佇列等功能,因為它更快,佔用RAM更少,是FreeRTOS自8.2以來推出的重大改進功能。

一、任務通知相關變數

1.1、TCB中的通知相關成員

FreeRTOS每個任務都有一個通知指示值,和一個32位通知值:

任務資料結構(TCB)中與佇列通知相關的成員

#if ( configUSE_TASK_NOTIFICATIONS == 1 )
    volatile uint32_t ulNotifiedValue;
    
volatile eNotifyValue eNotifyState; #endif
  • ulNotifiedValue就是任務中的通知值,任務通知實際上就是圍繞這個變數作文章,下面會以“通知值”來代替這個成員變數,
  • eNotifyState用來標誌任務是否在等待通知,它有以下3種情況
eNotified 任務已經被通知 帶傳送通知功能的函式都會首先把eNotifyState設定為eNotified,表示任務已經被通知
eWaitingNotification 任務正在等待通知 接收通知功能的函式會首先把eNotifyState設定為eWaitingNotification,表示任務已經阻塞了正在等待通知
eNotWaitingNotification 空狀態 表示任務即沒有收到新的通知,也沒有正在等待通知,接收通知功能函式在接收到通知處理後,會把eNotifyState設定為eWaitingNotification

根據上一節中的TCB我們的精簡,我們現在為TCB補上接下來會用到新的成員:

typedef struct tskTaskControlBlock
{
    volatile StackType_t    *pxTopOfStack; /*任務堆疊棧頂*/

    ListItem_t    xGenericListItem;    /*任務狀態列表項項引用的列表,指示任務狀態(準備態、阻塞態、掛起態)
*/ ListItem_t xEventListItem; /*狀態列表項*/ UBaseType_t uxPriority; /*任務優先順序*/ StackType_t *pxStack; /*任務堆疊起始地址*/ char pcTaskName[ configMAX_TASK_NAME_LEN ];/*任務名字*/ volatile uint32_t ulNotifiedValue; /*任務通知值*/ volatile eNotifyValue eNotifyState; /*通知狀態標誌*/ } tskTCB;

二、任務通知API函式

2.1、傳送通知

xTaskNotifyGive() 傳送通知,通知值設定為自增方式(每次呼叫通知值加1)
vTaskNotifyGiveFromISR() 上面函式的中斷版本
xTaskNotify()  傳送通知,可以自定義通知方式
 xTaskNotifyFromISR()  上面函式的中斷版本
 xTaskNotifyAndQuery()  傳送通知,自定義通知方式,並且讀出上一次的通知值
 xTaskNotifyAndQueryFromISR()  上面函式的中斷版本

  其中有5個API是巨集,它們關係如下:

  非中斷版本:

#define xTaskNotify( xTaskToNotify, ulValue, eAction )  xTaskGenericNotify( ( xTaskToNotify ), ( ulValue ), ( eAction ), NULL )
#define xTaskNotifyAndQuery( xTaskToNotify, ulValue, eAction, pulPreviousNotifyValue )  xTaskGenericNotify( ( xTaskToNotify ), ( ulValue ), ( eAction ), ( pulPreviousNotifyValue ) )
#define xTaskNotifyGive( xTaskToNotify ) xTaskGenericNotify( ( xTaskToNotify ), ( 0 ), eIncrement, NULL )

  中斷版本:

#define xTaskNotifyFromISR( xTaskToNotify, ulValue, eAction, pxHigherPriorityTaskWoken )  xTaskGenericNotifyFromISR( ( xTaskToNotify ), ( ulValue ), ( eAction ), NULL, ( pxHigherPriorityTaskWoken ) ) 
 #define xTaskNotifyAndQueryFromISR( xTaskToNotify, ulValue, eAction, pulPreviousNotificationValue, pxHigherPriorityTaskWoken )  xTaskGenericNotifyFromISR( ( xTaskToNotify ), ( ulValue ), ( eAction ), ( pulPreviousNotificationValue ), ( pxHigherPriorityTaskWoken ) )

  可以發現,實際上他們底層只有兩個函式,

    •   xTaskGenericNotify()
    •   xTaskGenericNotifyFromISR()

  再加上一個直接指向頂層的函式

    •   vTaskNotifyGiveFromISR()

  接下來我們直接看這3個函式,會更便於理解佇列通知以及使用

2.1.1生成通知訊號函式xTaskGenericNotify():

函式原型:

  BaseType_t xTaskGenericNotify( TaskHandle_t xTaskToNotify, uint32_t ulValue, eNotifyAction eAction,   uint32_t *pulPreviousNotificationValue )

 輸入引數:

xTaskToNotify 被通知的任務的控制代碼
ulValue 輸入值
eAction 進行通知方式
*pulPreviousNotificationValue 這個任務上一次的通知值

  其中引數eAction最為重要,它決定了我們以什麼方式傳送通知,我們檢視它是一個eNotifyAction型別的結構體,檢視這個結構體,可以留意到傳送通知的方式分為以下5種:

typedef enum
{
    eNoAction = 0,    
    eSetBits,
    eIncrement,
    eSetValueWithOverwrite,
    eSetValueWithoutOverwrite
} eNotifyAction;

現在我們來擷取xTaskGenericNotifyFromISR()一段操作通知值的程式碼,看看這5種訊號是怎麼改變通知值的:

            switch( eAction )
            {
                case eSetBits    :
                    pxTCB->ulNotifiedValue |= ulValue;
                    break;

                case eIncrement    :
                    ( pxTCB->ulNotifiedValue )++;
                    break;

                case eSetValueWithOverwrite    :
                    pxTCB->ulNotifiedValue = ulValue;
                    break;

                case eSetValueWithoutOverwrite :
                    if( eOriginalNotifyState != eNotified )
                    {
                        pxTCB->ulNotifiedValue = ulValue;
                    }
                    else
                    {
                        /* The value could not be written to the task. */
                        xReturn = pdFAIL;
                    }
                    break;

                case eNoAction :
                    /* The task is being notified without its notify value being
                    updated. */
                    break;
            }

原始碼分析(展開摺疊檢視)

這個函式主要做了3件事:

  1. 將TCB中的通知狀態標誌eNotifyState設定為已經收到通知的狀態
  2. 根據需求更新TCB中的通知值ulNotifiedValue
  3. 解除目標任務的阻塞狀態
#if( configUSE_TASK_NOTIFICATIONS == 1 )

    BaseType_t xTaskGenericNotify( TaskHandle_t xTaskToNotify, uint32_t ulValue, eNotifyAction eAction, uint32_t *pulPreviousNotificationValue )
    {
        /* 
        xTaskToNotify:被通知的任務控制代碼
        ulValue: 更新的通知值
        eAction: 列舉型別,指明更新通知值的方法,
        *pulPreviousNotificationValue:用於獲取上次的通知值
        */
    TCB_t * pxTCB;
    eNotifyValue eOriginalNotifyState;
    BaseType_t xReturn = pdPASS;

        configASSERT( xTaskToNotify );
        pxTCB = ( TCB_t * ) xTaskToNotify;

        taskENTER_CRITICAL();
        {
            if( pulPreviousNotificationValue != NULL )
            {
                *pulPreviousNotificationValue = pxTCB->ulNotifiedValue;
            }
            /*獲取上一次的通知狀態,儲存在區域性變數eOriginalNotifyState中,稍後覆蓋方法會用到*/
            eOriginalNotifyState = pxTCB->eNotifyState;
            
            /*更新TCB的通知狀態為eNotified(已通知狀態)*/                    /*【1】*/
            pxTCB->eNotifyState = eNotified;
            
            /*更新TCB的通知值(pxTCB->ulNotifiedValue),根據eAction的不同,達到傳輸不同種類通知的目的*/            /*【2】*/
            switch( eAction )
            {
                case eSetBits    :
                    pxTCB->ulNotifiedValue |= ulValue;
                    break;

                case eIncrement    :
                    ( pxTCB->ulNotifiedValue )++;
                    break;

                case eSetValueWithOverwrite    :
                    pxTCB->ulNotifiedValue = ulValue;
                    break;

                case eSetValueWithoutOverwrite :
                    if( eOriginalNotifyState != eNotified )
                    {
                        pxTCB->ulNotifiedValue = ulValue;
                    }
                    else
                    {
                        /* The value could not be written to the task. */
                        /* 值無法被寫入任務中 */
                        xReturn = pdFAIL;
                    }
                    break;

                case eNoAction:
                    /* The task is being notified without its notify value being
                    updated. */
                    /* 任務正在被通知,而它的通知值沒有被更新 */
                    break;
            }

            traceTASK_NOTIFY();

            /* If the task is in the blocked state specifically to wait for a
            notification then unblock it now. */
            /* 如果目標任務是阻塞狀態,特別是如果在等待通知,那麼解除阻塞 */
            if( eOriginalNotifyState == eWaitingNotification )                  /*【3】*/
            {
                ( void ) uxListRemove( &( pxTCB->xGenericListItem ) );
                prvAddTaskToReadyList( pxTCB );

                /* The task should not have been on an event list. */
                /* 任務不應該已經新增進事件列表 */
                configASSERT( listLIST_ITEM_CONTAINER( &( pxTCB->xEventListItem ) ) == NULL );

                #if( configUSE_TICKLESS_IDLE != 0 )
                {
                    /* If a task is blocked waiting for a notification then
                    xNextTaskUnblockTime might be set to the blocked task's time
                    out time.  If the task is unblocked for a reason other than
                    a timeout xNextTaskUnblockTime is normally left unchanged,
                    because it will automatically get reset to a new value when
                    the tick count equals xNextTaskUnblockTime.  However if
                    tickless idling is used it might be more important to enter
                    sleep mode at the earliest possible time - so reset
                    xNextTaskUnblockTime here to ensure it is updated at the
                    earliest possible time. */
                    /* 如果一個任務阻塞等待通知,那麼xNextTaskUnblockTime應該設定為阻塞任務時間外的時間。
                    如果任務因為一些原因(除了一個超時)被解除阻塞,xNextTaskUnblockTime通常保持不變。
                    因為當滴答計數器等於xNextTaskUnblockTime的時候,它會被重置為一個新的值。
                    無論如何,如果tickless idling 被使用,它可能是首先進入睡眠模式,
                    所以在這裡重置xNextTaskUnblockTime來確保它被更新*/
                    prvResetNextTaskUnblockTime();
                }
                #endif

                if( pxTCB->uxPriority > pxCurrentTCB->uxPriority )
                {
                    /* The notified task has a priority above the currently
                    executing task so a yield is required. */
                    /* 被通知的任務優先順序超過了當前執行中的任務,所以需要進行切換(切換到被通知的任務) */
                    taskYIELD_IF_USING_PREEMPTION();
                }
                else
                {
                    mtCOVERAGE_TEST_MARKER();
                }
            }
            else
            {
                mtCOVERAGE_TEST_MARKER();
            }
        }
        taskEXIT_CRITICAL();

        return xReturn;
    }

#endif /* configUSE_TASK_NOTIFICATIONS */
View Code

2.1.2、生成通知訊號函式中斷版本 xTaskGenericNotifyFromISR()

 函式原型:

  BaseType_t xTaskGenericNotifyFromISR( TaskHandle_t xTaskToNotify, uint32_t ulValue, eNotifyAction eAction, uint32_t *pulPreviousNotificationValue, BaseType_t *pxHigherPriorityTaskWoken )

作為xTaskGenericNotify()的中斷版本,xTaskGenericNotifyFromISR()中加了一些中段相關處理,我們可以看到,他們輸入引數都相同(增加一個pxHigherPriorityTaskWoken引數用於指示執行期間是否有任務切換髮生)。 所以這個函式實際上和xTaskGenericNotify()的操作相同。

  1. 將TCB中的通知狀態標誌eNotifyState設定為已經收到通知的狀態
  2. 根據需求更新TCB中的通知值ulNotifiedValue
  3. 解除目標任務的阻塞狀態

2.1.3、一個自增通知的中斷定製版 vTaskNotifyGiveFromISR():

函式原型:

  void vTaskNotifyGiveFromISR( TaskHandle_t xTaskToNotify, BaseType_t *pxHigherPriorityTaskWoken ) 這個函式是xTaskGenericNotifyFromISR()的壓縮定製版,去掉了3個輸入引數ulValue、eAction、pulPreviousNotificationValue和對應這3個引數相關的處理程式,因為它是特別為自增型通知定製的,與xTaskGenericNotifyFromISR()這個函式提高了效率,大概FreeRTOS作者認為自增通知是常用的通知型別,所以特意寫了這個優化版本的函式。 所以這個函式實際上也和xTaskGenericNotify()的操作相同,功能如下

  1. 將TCB中的通知狀態標誌eNotifyState設定為已經收到通知的狀態
  2. 根據需求更新TCB中的通知值ulNotifiedValue(自增)
  3. 解除目標任務的阻塞狀態
#if( configUSE_TASK_NOTIFICATIONS == 1 )

    void vTaskNotifyGiveFromISR( TaskHandle_t xTaskToNotify, BaseType_t *pxHigherPriorityTaskWoken )
    {
    TCB_t * pxTCB;
    eNotifyValue eOriginalNotifyState;
    UBaseType_t uxSavedInterruptStatus;

        configASSERT( xTaskToNotify );

        /* RTOS ports that support interrupt nesting have the concept of a
        maximum    system call (or maximum API call) interrupt priority.
        Interrupts that are    above the maximum system call priority are keep
        permanently enabled, even when the RTOS kernel is in a critical section,
        but cannot make any calls to FreeRTOS API functions.  If configASSERT()
        is defined in FreeRTOSConfig.h then
        portASSERT_IF_INTERRUPT_PRIORITY_INVALID() will result in an assertion
        failure if a FreeRTOS API function is called from an interrupt that has
        been assigned a priority above the configured maximum system call
        priority.  Only FreeRTOS functions that end in FromISR can be called
        from interrupts    that have been assigned a priority at or (logically)
        below the maximum system call interrupt priority.  FreeRTOS maintains a
        separate interrupt safe API to ensure interrupt entry is as fast and as
        simple as possible.  More information (albeit Cortex-M specific) is
        provided on the following link:
        http://www.freertos.org/RTOS-Cortex-M3-M4.html */
        
        portASSERT_IF_INTERRUPT_PRIORITY_INVALID();

        pxTCB = ( TCB_t * ) xTaskToNotify;

        uxSavedInterruptStatus = portSET_INTERRUPT_MASK_FROM_ISR();
        {
            eOriginalNotifyState = pxTCB->eNotifyState;
            pxTCB->eNotifyState = eNotified;                            /*【1】*/

            /* 'Giving' is equivalent to incrementing a count in a counting
            semaphore. */
            /* 給予是等價於在計數訊號量中增加一個計數 */
            ( pxTCB->ulNotifiedValue )++;                               /*【2】*/
            
            traceTASK_NOTIFY_GIVE_FROM_ISR();

            /* If the task is in the blocked state specifically to wait for a
            notification then unblock it now. */
            /* 如果任務在阻塞狀態,明確地等待一個通知,然後馬上解除阻塞*/
            if( eOriginalNotifyState == eWaitingNotification )          /*【3】*/
            {
                /* The task should not have been on an event list. */
                /* 任務不應該已經加入事件列表了 */
                configASSERT( listLIST_ITEM_CONTAINER( &( pxTCB->xEventListItem ) ) == NULL );

                if( uxSchedulerSuspended == ( UBaseType_t ) pdFALSE )
                {
                    ( void ) uxListRemove( &( pxTCB->xGenericListItem ) );
                    prvAddTaskToReadyList( pxTCB );
                }
                else
                {
                    /* The delayed and ready lists cannot be accessed, so hold
                    this task pending until the scheduler is resumed. */
                    /* 延時和準備列表無法被訪問,所以保持這個任務掛起,知道排程器被恢復 */
                    vListInsertEnd( &( xPendingReadyList ), &( pxTCB->xEventListItem ) );
                }
                
                if( pxTCB->uxPriority > pxCurrentTCB->uxPriority )
                {
                    /* The notified task has a priority above the currently
                    executing task so a yield is required. */
                    /* 通知任務已經比當前執行任務更高,所以需要進行切換 */
                    if( pxHigherPriorityTaskWoken != NULL )
                    {
                        *pxHigherPriorityTaskWoken = pdTRUE;
                    }
                }
                else
                {
                    mtCOVERAGE_TEST_MARKER();
                }
            }
        }
        portCLEAR_INTERRUPT_MASK_FROM_ISR( uxSavedInterruptStatus );
    }

#endif /* configUSE_TASK_NOTIFICATIONS */
View Code

 接下來我們回到API函式,看看這6個API的功能,以及它們呼叫的是哪個底層函式:

 2.2接收通知

ulTaskNotifyTake()  提取通知  

適用於二值通知(eNoAction)和自增通知(eIncrement)

 xTaskNotifyWait()  等待通知  適用所有通知,但不附帶自增通知的自減功能

2.2.1、ulTaskNotifyTake()

函式原型:

  uint32_t ulTaskNotifyTake( BaseType_t xClearCountOnExit, TickType_t xTicksToWait )

輸入引數:

BaseType_t xClearCountOnExit 退出時是否清除
TickType_t xTicksToWait 最大等待時間
  • xClearCountOnExit:這個引數可以傳入pdTRUE或者pdFALSE

  

  • xTicksToWait:在等待通知的時候,任務會進入阻塞狀態,任務進入阻塞狀態的最大時間(以Tick為單位,可以用pdMS_TO_TICKS()將毫秒換為tick)

原始碼分析:(展開摺疊檢視)

  這個函式主要做了4件事:

  1.  改變TCB中的eNotifyState為正在等待通知狀態
  2. 讓任務進入阻塞或掛起狀態等待通知
  3. 收到通知後,對通知值ulNotifiedValue進行操作(刪除或自減)
  4. 改變TCB中的eNotifyState為空狀態,因為讀取通知的操作已經完成了
#if( configUSE_TASK_NOTIFICATIONS == 1 )

    uint32_t ulTaskNotifyTake( BaseType_t xClearCountOnExit, TickType_t xTicksToWait )
    {
    TickType_t xTimeToWake;
    uint32_t ulReturn;

        taskENTER_CRITICAL();
        {
            /* Only block if the notification count is not already non-zero. */
            /* 僅僅當通知值為0的時候, 才進行阻塞操作 */
            if( pxCurrentTCB->ulNotifiedValue == 0UL )
            {
                /* Mark this task as waiting for a notification. */     
                /* 遮蔽這個任務來等待通知 */
                pxCurrentTCB->eNotifyState = eWaitingNotification;   /*改變TCB中的eNotifyState 為 eWaitingNotification*/   /*【1】*/

                if( xTicksToWait > ( TickType_t ) 0 )                                  
                {
                    /* The task is going to block.  First it must be removed
                    from the ready list. */
                    /* 任務將會阻塞。 但首先必須從準備列表移除 */
                    if( uxListRemove( &( pxCurrentTCB->xGenericListItem ) ) == ( UBaseType_t ) 0 )
                    {
                        /* The current task must be in a ready list, so there is
                        no need to check, and the port reset macro can be called
                        directly. */
                        /* 當前任務必須在準備列表,所以沒有必要再檢查,介面重置巨集可以被直接呼叫 */
                        portRESET_READY_PRIORITY( pxCurrentTCB->uxPriority, uxTopReadyPriority );
                    }
                    else
                    {
                        mtCOVERAGE_TEST_MARKER();
                    }

                    #if ( INCLUDE_vTaskSuspend == 1 )                    /*【2】*/
                    {
                        /* 如果設定了 xTicksToWait 為 portMAX_DELAY。任務會直接掛起*/
                        if( xTicksToWait == portMAX_DELAY )
                        {
                            /* Add the task to the suspended task list instead
                            of a delayed task list to ensure the task is not
                            woken by a timing event.  It will block
                            indefinitely. */
                            /* 把任務新增到掛起任務列表,而不是延時任務列表(阻塞狀態會倒計時)。這是為了確認任務沒有被時間事件喚醒。任務會被無限期的阻塞(直接掛起) */
                            vListInsertEnd( &xSuspendedTaskList, &( pxCurrentTCB->xGenericListItem ) );
                        }
                        else
                        {
                            /* Calculate the time at which the task should be
                            woken if no notification events occur.  This may
                            overflow but this doesn't matter, the scheduler will
                            handle it. */
                            /* 如果沒有通知事件發生,計算任務應該被喚醒的時間
                            這個可能溢位,但是沒有關係,排程器會處理它的*/
                            
                            xTimeToWake = xTickCount + xTicksToWait;        /*計算喚醒時間*/
                            prvAddCurrentTaskToDelayedList( xTimeToWake );  /*把計算好的時間新增到延時列表。交給排程器處理*/
                        }
                    }
                    #else /* INCLUDE_vTaskSuspend */
                    {
                            /* Calculate the time at which the task should be
                            woken if the event does not occur.  This may
                            overflow but this doesn't matter, the scheduler will
                            handle it. */
                            /* 如果沒有通知事件發生,計算任務應該被喚醒的時間
                                這個可能溢位,但是沒有關係,排程器會處理它的*/
                            xTimeToWake = xTickCount + xTicksToWait;
                            prvAddCurrentTaskToDelayedList( xTimeToWake );
                    }
                    #endif /* INCLUDE_vTaskSuspend */

                    traceTASK_NOTIFY_TAKE_BLOCK();

                    /* All ports are written to allow a yield in a critical
                    section (some will yield immediately, others wait until the
                    critical section exits) - but it is not something that
                    application code should ever do. */
                    /* 在臨界區,所有介面被寫入,來立刻允許一次切換(有一些會馬上切換,其他會等待知道重要部分退出) , 但它不是一些應用程式碼應該做的重要的事*/
                    portYIELD_WITHIN_API();
                }
                else
                {
                    mtCOVERAGE_TEST_MARKER();
                }
            }
            else
            {
                mtCOVERAGE_TEST_MARKER();
            }
        }
        taskEXIT_CRITICAL();

        taskENTER_CRITICAL();
        {
            traceTASK_NOTIFY_TAKE();
            ulReturn = pxCurrentTCB->ulNotifiedValue;/*設定返回值為收到的通知值*/  

            if( ulReturn != 0UL )                                        /*【3】*/
            {
                if( xClearCountOnExit != pdFALSE )
                {
                    pxCurrentTCB->ulNotifiedValue = 0UL;/*清零通知值*/
                }
                else
                {
                    ( pxCurrentTCB->ulNotifiedValue )--;/*減少通知值(對自增通知的特殊處理方法)*/
                }
            }
            else
            {
                mtCOVERAGE_TEST_MARKER();
            }

            pxCurrentTCB->eNotifyState = eNotWaitingNotification;/* 清除等待/接收通知狀態 */ /*【4】*/
        }
        taskEXIT_CRITICAL();

        return ulReturn;
    }

#endif /* configUSE_TASK_NOTIFICATIONS */
View Code

  *在我們檢視原始碼的時候,我們可以留意到,當我們設定輸入引數為xTicksToWait為portMAX_DELAY的時候,而且INCLUDE_vTaskSuspend(啟用掛起狀態)巨集定義為1的時候任務不是阻塞,而是直接掛起

                    #if ( INCLUDE_vTaskSuspend == 1 )                    /*【2】*/
                    {
                        /* 如果設定了 xTicksToWait 為 portMAX_DELAY。任務會直接掛起*/
                        if( xTicksToWait == portMAX_DELAY )
                        {
                            /* Add the task to the suspended task list instead
                            of a delayed task list to ensure the task is not
                            woken by a timing event.  It will block
                            indefinitely. */
                            /* 把任務新增到掛起任務列表,而不是延時任務列表(阻塞狀態會倒計時)。這是為了確認任務沒有被時間事件喚醒。任務會被無限期的阻塞(直接掛起) */
                            vListInsertEnd( &xSuspendedTaskList, &( pxCurrentTCB->xGenericListItem ) );
                        }
                        else
                        {
                            /* Calculate the time at which the task should be
                            woken if no notification events occur.  This may
                            overflow but this doesn't matter, the scheduler will
                            handle it. */
                            /* 如果沒有通知事件發生,計算任務應該被喚醒的時間
                            這個可能溢位,但是沒有關係,排程器會處理它的*/
                            
                            xTimeToWake = xTickCount + xTicksToWait;        /*計算喚醒時間*/
                            prvAddCurrentTaskToDelayedList( xTimeToWake );  /*把計算好的時間新增到延時列表。交給排程器處理*/
                        }
                    }
View Code

官方例子:

 

2.2.2、xTaskNotifyWait()

  BaseType_t xTaskNotifyWait( uint32_t ulBitsToClearOnEntry, uint32_t ulBitsToClearOnExit, uint32_t *pulNotificationValue, TickType_t xTicksToWait )

輸入引數:

  

  • ulBitsToClearOnEntry:在進入阻塞之前把指定的位元清除
  • ulBitsToClearOnExit:在接收到通知並處理後把指定的位元位清除
  • *pulNotificationValue:用於儲存新到的通知值
  • xTicksToWait:最大阻塞時間

返回值:

  兩種情況

  

原始碼分析:(展開摺疊檢視)

  1. 這個函式和ulTaskNotifyTake很像,主要做了5件事:
  2. 根據ulBitsToClearOnEntry先清除一下通知值相應的位
  3. 改變TCB中的eNotifyState為正在等待通知狀態
  4. 讓任務進入阻塞或掛起狀態等待通知
  5. 收到通知後,對通知值ulNotifiedValue進行操作(根據ulBitsToClearOnExit清除相應位)
  6. 改變TCB中的eNotifyState為空狀態,因為讀取通知的操作已經完成了
#if( configUSE_TASK_NOTIFICATIONS == 1 )
    
    BaseType_t xTaskNotifyWait( uint32_t ulBitsToClearOnEntry, uint32_t ulBitsToClearOnExit, uint32_t *pulNotificationValue, TickType_t xTicksToWait )
    {
    TickType_t xTimeToWake;
    BaseType_t xReturn;
        
        /* */
        taskENTER_CRITICAL();
        {
            /* Only block if a notification is not already pending. */
            /* 只有沒收到通知,才會阻塞任務(換句話說,如果現在已經收到通知了就不需要阻塞任務了,直接處理就好了) */
            if( pxCurrentTCB->eNotifyState != eNotified )
            {
                /* Clear bits in the task's notification value as bits may get
                set    by the notifying task or interrupt.  This can be used to
                clear the value to zero. */
                /* 清除任務通知值的位元位,因為這些位元肯能被通知任務或者中斷置位了。
                    這個可以用於把值清0*/
                pxCurrentTCB->ulNotifiedValue &= ~ulBitsToClearOnEntry;                         /*【1】*/

                /* Mark this task as waiting for a notification. */
                /* 記錄這個任務為等待通知的狀態*/
                pxCurrentTCB->eNotifyState = eWaitingNotification;                              /*【2】*/

                if( xTicksToWait > ( TickType_t ) 0 )
                {
                    /* The task is going to block.  First it must be removed
                    from the    ready list. */
                    /* 任務馬上就要阻塞了,首先要把它移出準備列表 */
                    if( uxListRemove( &( pxCurrentTCB->xGenericListItem ) ) == ( UBaseType_t ) 0 )
                    {
                        /* The current task must be in a ready list, so there is
                        no need to check, and the port reset macro can be called
                        directly. */
                        /* 當前任務肯定在準備列表中 ,所以沒有必要檢查了,介面重置巨集可以被直接呼叫 */
                        portRESET_READY_PRIORITY( pxCurrentTCB->uxPriority, uxTopReadyPriority );
                    }
                    else
                    {
                        mtCOVERAGE_TEST_MARKER();
                    }

                    #if ( INCLUDE_vTaskSuspend == 1 )                                            /*【3】*/
                    {
                        if( xTicksToWait == portMAX_DELAY )
                        {
                            /* Add the task to the suspended task list instead
                            of a delayed task list to ensure the task is not
                            woken by a timing event.  It will block
                            indefinitely. */
                            /* 把任務加入掛起任務列表,而不是延時任務列表。這是為了確保任務沒有被時間事件喚醒
                                這個任務會無限阻塞 */
                            vListInsertEnd( &xSuspendedTaskList, &( pxCurrentTCB->xGenericListItem ) );
                        }
                        else
                        {
                            /* Calculate the time at which the task should be
                            woken if no notification events occur.  This may
                            overflow but this doesn't matter, the scheduler will
                            handle it. */
                            /* 計算在如果沒有通知事件,發生任務應該被喚醒的時間 。
                            這個可能會導致溢位,但是沒有關係。排程器會處理它的*/
                            xTimeToWake = xTickCount + xTicksToWait;
                            prvAddCurrentTaskToDelayedList( xTimeToWake );
                        }
                    }
                    #else /* INCLUDE_vTaskSuspend */
                    {
                            /* Calculate the time at which the task should be
                            woken if the event does not occur.  This may
                            overflow but this doesn't matter, the scheduler will
                            handle it. */
                            /* 計算在如果沒有通知事件,發生任務應該被喚醒的時間 。
                            這個可能會導致溢位,但是沒有關係。排程器會處理它的*/
                            xTimeToWake = xTickCount + xTicksToWait;
                            prvAddCurrentTaskToDelayedList( xTimeToWake );
                    }
                    #endif /* INCLUDE_vTaskSuspend */

                    traceTASK_NOTIFY_WAIT_BLOCK();
                    
                    /* All ports are written to allow a yield in a critical
                    section (some will yield immediately, others wait until the
                    critical section exits) - but it is not something that
                    application code should ever do. */
                    /* 寫入所有介面,允許在臨界區進行一次切換*/
                    portYIELD_WITHIN_API();
                }
                else
                {
                    mtCOVERAGE_TEST_MARKER();
                }
            }
            else
            {
                mtCOVERAGE_TEST_MARKER();
            }
        }
        taskEXIT_CRITICAL();

        taskENTER_CRITICAL();
        {
            traceTASK_NOTIFY_WAIT();
            
            if( pulNotificationValue != NULL )
            {
                /* Output the current notification value, which may or may not
                have changed. */
                /* 設定pulNotificationValue引數為當前通知值,不管它有沒有改變*/
                *pulNotificationValue = pxCurrentT