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(支持动态内存申请),或者简单地未定义,使这个函数可用。