FreeRTOS之xTaskCreate()

xTaskCreate()函數解析

task. h

 BaseType_t xTaskCreate(    TaskFunction_t pvTaskCode,
                            const char * const pcName,
                            configSTACK_DEPTH_TYPE usStackDepth,
                            void *pvParameters,
                            UBaseType_t uxPriority,
                            TaskHandle_t *pxCreatedTask
                          );

總結

創建新的任務實例。
每個任務都需要RAM來保存任務狀態(任務控制塊,或TCB),並被任務用作其堆棧。如果任務是使用xTaskCreate()創建的,則需要從FreeRTOS的堆中自動分配RAM。如果使用xTaskCreateStatic()創建任務,則由應用程序編寫器提供RAM,這將導致兩個額外的函數參數,但允許在編譯時靜態分配RAM。
新創建的任務最初處於就緒狀態,但如果沒有更高優先級的任務可以運行,則會立即成爲正在運行的狀態任務。
創建任務可以在啓動調度程序之前和之後。

參數

參數 功能
pvTaskCode 任務函數
pcName 任務名
usStackDepth 任務棧大小
pvParameters 任務參數
uxPriority 任務優先級
pxCreatedTask 任務句柄

返回值

返回值 意義
pdPass 表示任務已經創建成功。
errCOULD_NOT_ALLOCATE_REQUIRED_MEMORY 表示無法創建任務,因爲FreeRTOS沒有足夠的堆內存來分配任務數據結構和堆棧。如果項目中包含heap_1.c、heap_2.c或heap_4.c,FreeRTOSConfig中的configTOTAL_HEAP_SIZE定義可用堆的總量。使用vApplicationMallocFailedHook()回調函數(或“hook”)可以捕獲分配內存失敗,使用xPortGetFreeHeapSize() API函數可以查詢剩餘的空閒堆內存數量。如果項目中包含heap_3.c,則鏈接器配置將定義總堆大小。

使用例程

/* Task to be created. */
void vTaskCode( void * pvParameters )
{
    /* The parameter value is expected to be 1 as 1 is passed in the
    pvParameters value in the call to xTaskCreate() below. configASSERT( ( ( uint32_t ) pvParameters ) == 1 );

    for( ;; )
    {
        /* Task code goes here. */
    }
}

/* Function that creates a task. */
void vOtherFunction( void )
{
BaseType_t xReturned;
TaskHandle_t xHandle = NULL;

    /* Create the task, storing the handle. */
    xReturned = xTaskCreate(
                    vTaskCode,       /* Function that implements the task. */
                    "NAME",          /* Text name for the task. */
                    STACK_SIZE,      /* Stack size in words, not bytes. */
                    ( void * ) 1,    /* Parameter passed into the task. */
                    tskIDLE_PRIORITY,/* Priority at which the task is created. */
                    &xHandle );      /* Used to pass out the created task's handle. */

    if( xReturned == pdPASS )
    {
        /* The task was created.  Use the task's handle to delete the task. */vTaskDelete( xHandle );
    }
}

說明

在FreeRTOSConfig.h中,configSUPPORT_DYNAMIC_ALLOCATION必須設置爲1(支持動態內存申請),或者簡單地未定義,使這個函數可用。

Freertos更多精彩

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章