return osPriorityError; #endif }
`vTaskPrioritySet`设置任务优先级 封装后是`osThreadSetPriority`,如下:
osStatus osThreadSetPriority (osThreadId thread_id, osPriority priority) { #if (INCLUDE_vTaskPrioritySet == 1) vTaskPrioritySet(thread_id, makeFreeRtosPriority(priority)); return osOK; #else return osErrorOS; #endif }
### 延时任务
`vTaskDelay`相对延时封装后`osDelay`,如下:
/*********************** Generic Wait Functions *******************************/ /** * @brief Wait for Timeout (Time Delay) * @param millisec time delay value * @retval status code that indicates the execution status of the function. */ osStatus osDelay (uint32_t millisec) { #if INCLUDE_vTaskDelay TickType_t ticks = millisec / portTICK_PERIOD_MS;
vTaskDelay(ticks ? ticks : 1); /* Minimum delay = 1 tick */
return osOK; #else (void) millisec;
return osErrorResource; #endif }
`vTaskDelayuntil`绝对延时封装后`osDelayUntil`,如下:
/** * @brief Delay a task until a specified time * @param PreviousWakeTime Pointer to a variable that holds the time at which the * task was last unblocked. PreviousWakeTime must be initialised with the current time * prior to its first use (PreviousWakeTime = osKernelSysTick() ) * @param millisec time delay value * @retval status code that indicates the execution status of the function. */ osStatus osDelayUntil (uint32_t *PreviousWakeTime, uint32_t millisec) { #if INCLUDE_vTaskDelayUntil TickType_t ticks = (millisec / portTICK_PERIOD_MS); vTaskDelayUntil((TickType_t *) PreviousWakeTime, ticks ? ticks : 1);
return osOK; #else (void) millisec; (void) PreviousWakeTime;
return osErrorResource; #endif }
## FreeRTOS 任务源码简析
### 任务状态
在分析任务源码之前,先得了解一下FreeRTOS中任务的四种基本状态:
运行态,挂起态,阻塞态,就绪态。
在官方文档中:

### 任务控制块
FreeRTOS 的每个任务都有一些属性需要存储,把这些属性集合在一起的结构体叫做任务控制块TCB\_t (Task control block),源码如下:
/* * Task control block. A task control block (TCB) is allocated for each task, * and stores task state information, including a pointer to the task's context * (the task's run time environment, including register values) */ typedef struct tskTaskControlBlock { volatile StackType_t *pxTopOfStack; /*< Points to the location of the last item placed on the tasks stack. THIS MUST BE THE FIRST MEMBER OF THE TCB STRUCT. */
#if ( portUSING\_MPU\_WRAPPERS == 1 )
xMPU_SETTINGS xMPUSettings; /\*< The MPU settings are defined as part of the port layer. THIS MUST BE THE SECOND MEMBER OF THE TCB STRUCT. \*/
#endif
ListItem_t xStateListItem; /\*< The list that the state list item of a task is reference from denotes the state of that task (Ready, Blocked, Suspended ). \*/
ListItem_t xEventListItem; /\*< Used to reference a task from an event list. \*/
UBaseType_t uxPriority; /\*< The priority of the task. 0 is the lowest priority. \*/
StackType_t \*pxStack; /\*< Points to the start of the stack. \*/
char pcTaskName[ configMAX_TASK_NAME_LEN ];/\*< Descriptive name given to the task when created. Facilitates debugging only. \*/ /\*lint !e971 Unqualified char types are allowed for strings and single characters only. \*/
#if ( ( portSTACK\_GROWTH > 0 ) || ( configRECORD\_STACK\_HIGH\_ADDRESS == 1 ) )
StackType_t \*pxEndOfStack; /\*< Points to the highest valid address for the stack. \*/
#endif
#if ( portCRITICAL\_NESTING\_IN\_TCB == 1 )
UBaseType_t uxCriticalNesting; /\*< Holds the critical section nesting depth for ports that do not maintain their own count in the port layer. \*/
#endif
#if ( configUSE\_TRACE\_FACILITY == 1 )
UBaseType_t uxTCBNumber; /\*< Stores a number that increments each time a TCB is created. It allows debuggers to determine when a task has been deleted and then recreated. \*/
UBaseType_t uxTaskNumber; /\*< Stores a number specifically for use by third party trace code. \*/
#endif
#if ( configUSE\_MUTEXES == 1 )
UBaseType_t uxBasePriority; /\*< The priority last assigned to the task - used by the priority inheritance mechanism. \*/
UBaseType_t uxMutexesHeld;
#endif
#if ( configUSE\_APPLICATION\_TASK\_TAG == 1 )
TaskHookFunction_t pxTaskTag;
#endif
#if( configNUM\_THREAD\_LOCAL\_STORAGE\_POINTERS > 0 )
void \*pvThreadLocalStoragePointers[ configNUM_THREAD_LOCAL_STORAGE_POINTERS ];
#endif
#if( configGENERATE\_RUN\_TIME\_STATS == 1 )
uint32_t ulRunTimeCounter; /\*< Stores the amount of time the task has spent in the Running state. \*/
#endif
#if ( configUSE\_NEWLIB\_REENTRANT == 1 )
/\* Allocate a Newlib reent structure that is specific to this task.
Note Newlib support has been included by popular demand, but is not used by the FreeRTOS maintainers themselves. FreeRTOS is not responsible for resulting newlib operation. User must be familiar with newlib and must provide system-wide implementations of the necessary stubs. Be warned that (at the time of writing) the current newlib design implements a system-wide malloc() that must be provided with locks. */ struct _reent xNewLib_reent; #endif
#if( configUSE\_TASK\_NOTIFICATIONS == 1 )
volatile uint32_t ulNotifiedValue;
volatile uint8_t ucNotifyState;
#endif
/\* See the comments above the definition of
tskSTATIC_AND_DYNAMIC_ALLOCATION_POSSIBLE. */ #if( tskSTATIC_AND_DYNAMIC_ALLOCATION_POSSIBLE != 0 ) /*lint !e731 Macro has been consolidated for readability reasons. */ uint8_t ucStaticallyAllocated; /*< Set to pdTRUE if the task is a statically allocated to ensure no attempt is made to free the memory. */ #endif
#if( INCLUDE\_xTaskAbortDelay == 1 )
uint8_t ucDelayAborted;
#endif
} tskTCB;
/* The old tskTCB name is maintained above then typedefed to the new TCB_t name below to enable the use of older kernel aware debuggers. */ typedef tskTCB TCB_t;
| pxTopOfStack | 任务堆栈栈顶 |
| --- | --- |
| xStateListItem | 状态列表项 |
| xEventListItem | 事件列表项 |
| uxPriority | 任务优先级 |
| \*pxStack | 任务栈起始地址 |
| pcTaskName[16] | 任务名称 |
| \*pxEndOfStack | 任务堆栈栈底 |
状态列表项 :
每个任务都有4种状态,FreeRTOS 使用一种高效的数据结构双向链表保存任务的状态,Linux中也是。
事件列表项 :
信号量,消息队列,软件定时器等事件的管理
### 任务创建流程分析
任务创建流程如下图所示:

在分析FreeRTOS 任务创建源码之前,我们得先了解一下栈的不同类型。
#### 栈的四种类型
不同的硬件平台stack的增长方式不同,总的来说是有4种增长方式:
满减栈、满增栈、空减栈、空增栈。
满减栈:栈指针指向最后压入栈的数据,数据入栈时,sp先减一再入栈。
满增栈:栈指针指向最后压入栈的数据,数据入栈时,sp先加一再入栈。
空减栈:栈指针指向下一个将要放入数据的位置,数据入栈时,先入栈sp再减一。
空增栈:栈指针指向下一个将要放入数据的位置,数据入栈时,先入栈sp再加一。
满栈进栈是先移动指针再存;满栈出栈是先出数据再移动指针;
空栈进栈先存再移动指针;空栈出栈先移动指针再取数据。
ARM M3,M4内核使用的是 满减栈。
#### 任务创建源码分析
我们在源码中直接使用注释分析:
#if( configSUPPORT_DYNAMIC_ALLOCATION == 1 )
BaseType_t xTaskCreate( TaskFunction_t pxTaskCode,
const char \* const pcName, /\*lint !e971 Unqualified char types are allowed for strings and single characters only. \*/
const configSTACK_DEPTH_TYPE usStackDepth,
void \* const pvParameters,
UBaseType_t uxPriority,
TaskHandle_t \* const pxCreatedTask )
{
TCB_t \*pxNewTCB;
BaseType_t xReturn;
/\* If the stack grows down then allocate the stack then the TCB so the stack
does not grow into the TCB. Likewise if the stack grows up then allocate the TCB then the stack. 根据自己的硬件平台堆栈增长方式来判断使用那一部分编译, 堆栈增长方式: 1、满减栈 2、满增栈 3、空减栈 4、空增栈 #define portSTACK_GROWTH ( -1 ) 表示满减栈 */ #if( portSTACK_GROWTH > 0 ) { /* Allocate space for the TCB. Where the memory comes from depends on the implementation of the port malloc function and whether or not static allocation is being used. 任务栈内存分配 */ pxNewTCB = ( TCB_t * ) pvPortMalloc( sizeof( TCB_t ) );
if( pxNewTCB != NULL )
{
/\* Allocate space for the stack used by the task being created.
The base of the stack memory stored in the TCB so the task can be deleted later if required. 任务控制块内存分配 */ pxNewTCB->pxStack = ( StackType_t * ) pvPortMalloc( ( ( ( size_t ) usStackDepth ) * sizeof( StackType_t ) ) ); /*lint !e961 MISRA exception as the casts are only redundant for some ports. */
if( pxNewTCB->pxStack == NULL )
{
/\* Could not allocate the stack. Delete the allocated TCB. \*/
vPortFree( pxNewTCB );
pxNewTCB = NULL;
}
}
}
#else
/\* portSTACK\_GROWTH \*/
/\*
M3,M4中使用的下面这种
#define portSTACK_TYPE uint32_t typedef portSTACK_TYPE StackType_t;
每个内存是4个字节(StackType_t),所以创建堆栈是按照字来分配的 默认的是128 x 4 = 512字节;
*/ { StackType_t *pxStack;
/\* Allocate space for the stack used by the task being created. \*/
pxStack = ( StackType_t \* ) pvPortMalloc( ( ( ( size_t ) usStackDepth ) \* sizeof( StackType_t ) ) ); /\*lint !e961 MISRA exception as the casts are only redundant for some ports. \*/
if( pxStack != NULL )
{
/\*
Allocate space for the TCB. 根据TCB的大小还得分配空间 */ pxNewTCB = ( TCB_t * ) pvPortMalloc( sizeof( TCB_t ) ); /*lint !e961 MISRA exception as the casts are only redundant for some paths. */
if( pxNewTCB != NULL )
{
/\* Store the stack location in the TCB.
赋值栈地址 */ pxNewTCB->pxStack = pxStack; } else { /* The stack cannot be used as the TCB was not created. Free it again. 释放栈空间 */ vPortFree( pxStack ); } } else { pxNewTCB = NULL; } } #endif /* portSTACK_GROWTH */
if( pxNewTCB != NULL )
{
#if( tskSTATIC\_AND\_DYNAMIC\_ALLOCATION\_POSSIBLE != 0 ) /\*lint !e731 Macro has been consolidated for readability reasons. \*/
{
/\* Tasks can be created statically or dynamically, so note this
task was created dynamically in case it is later deleted. */ pxNewTCB->ucStaticallyAllocated = tskDYNAMICALLY_ALLOCATED_STACK_AND_TCB; } #endif /* configSUPPORT_STATIC_ALLOCATION */ /* 新建任务初始化 初始化任务控制块 初始化任务堆栈 */ prvInitialiseNewTask( pxTaskCode, pcName, ( uint32_t ) usStackDepth, pvParameters, uxPriority, pxCreatedTask, pxNewTCB, NULL ); /* 把任务添加到就绪列表中 */ prvAddNewTaskToReadyList( pxNewTCB ); xReturn = pdPASS; } else { xReturn = errCOULD_NOT_ALLOCATE_REQUIRED_MEMORY; }
return xReturn;
}
#endif /* configSUPPORT_DYNAMIC_ALLOCATION */
### 任务删除流程分析

#### 临界段
一种保护机制,代码的临界段也称为临界区,指处理时不可分割的代码区域,一旦这部分代码开始执行,则不允许任何中断打断。为确保临界段代码的执行不被中断,在进入临界段之前须关中断,而临界段代码执行完毕后,要立即打开中断。
在OS中,除了外部中断能将正在运行的代码打断,还有线程的调度——PendSV,系统产生 PendSV中断,在 PendSV Handler 里面实现线程的切换。我们要将这项东西屏蔽掉,保证当前只有一个线程在使用临界资源。
FreeRTOS对中断的开和关是通过操作 BASEPRI 寄存器来实现的,即大于等于 BASEPRI 的值的中断会被屏蔽,小于 BASEPRI 的值的中断则不会被屏蔽。这样子的好处就是用户可以设置 BASEPRI 的值来选择性的给一些非常紧急的中断留一条后路。
FreeRTOS 进入临界段 屏蔽中断:
/*-----------------------------------------------------------*/
portFORCE_INLINE static void vPortRaiseBASEPRI( void ) { uint32_t ulNewBASEPRI;
__asm volatile
(
" mov %0, %1 \n" \
" msr basepri, %0 \n" \
" isb \n" \
" dsb \n" \
:"=r" (ulNewBASEPRI) : "i" ( configMAX_SYSCALL_INTERRUPT_PRIORITY ) : "memory"
);
}
FreeRTOS 退出临界段 打开中断:
*-----------------------------------------------------------*/
portFORCE_INLINE static void vPortSetBASEPRI( uint32_t ulNewMaskValue ) { __asm volatile ( " msr basepri, %0 " :: "r" ( ulNewMaskValue ) : "memory" ); }
#### 任务删除源码分析
我们在源码中直接使用注释分析:
#if ( INCLUDE_vTaskDelete == 1 )
void vTaskDelete( TaskHandle_t xTaskToDelete )
{
TCB_t \*pxTCB;
/\*
进入临界段 */ taskENTER_CRITICAL(); { /* If null is passed in here then it is the calling task that is being deleted. 获取任务控制块 -----参数传入的是任务句柄 判断是任务本身,还是其他任务 */ pxTCB = prvGetTCBFromHandle( xTaskToDelete );
/\*
Remove task from the ready list. 从就绪列表中移除 */ if( uxListRemove( &( pxTCB->xStateListItem ) ) == ( UBaseType_t ) 0 ) { taskRESET_READY_PRIORITY( pxTCB->uxPriority ); } else { mtCOVERAGE_TEST_MARKER(); }
/\*
Is the task waiting on an event also? 从事件列表中移除 */ if( listLIST_ITEM_CONTAINER( &( pxTCB->xEventListItem ) ) != NULL ) { ( void ) uxListRemove( &( pxTCB->xEventListItem ) ); } else { mtCOVERAGE_TEST_MARKER(); }
/\* Increment the uxTaskNumber also so kernel aware debuggers can
detect that the task lists need re-generating. This is done before portPRE_TASK_DELETE_HOOK() as in the Windows port that macro will not return. */ uxTaskNumber++; /* 如果是删除当前任务 */ if( pxTCB == pxCurrentTCB ) { /* A task is deleting itself. This cannot complete within the task itself, as a context switch to another task is required. Place the task in the termination list. The idle task will check the termination list and free up any memory allocated by the scheduler for the TCB and stack of the deleted task. 删除任务本身不能立即删除,在空闲任务中删除 就把任务添加到等待删除的任务列表中 */ vListInsertEnd( &xTasksWaitingTermination, &( pxTCB->xStateListItem ) );
/\* Increment the ucTasksDeleted variable so the idle task knows
there is a task that has been deleted and that it should therefore check the xTasksWaitingTermination list. 给空间任务一个标记 */ ++uxDeletedTasksWaitingCleanUp;
/\* The pre-delete hook is primarily for the Windows simulator,
in which Windows specific clean up operations are performed, after which it is not possible to yield away from this task - hence xYieldPending is used to latch that a context switch is required. 钩子函数----用户自己实现 */ portPRE_TASK_DELETE_HOOK( pxTCB, &xYieldPending ); } else { --uxCurrentNumberOfTasks; prvDeleteTCB( pxTCB );
/\* Reset the next expected unblock time in case it referred to
the task that has just been deleted. 复位任务锁定时间 ----时间片 操作系统会记录一个最新的时间, 根据最新的时间,进行调度,所以删除任务后,要更新锁定时间 */ prvResetNextTaskUnblockTime(); }
traceTASK\_DELETE( pxTCB );
}
/\*退出临界段\*/
taskEXIT\_CRITICAL();
/\* Force a reschedule if it is the currently running task that has just been deleted.
判断调度器是否开启 */ if( xSchedulerRunning != pdFALSE ) { /* 如果是删除任务本身,马上进行任务调度(释放CPU的使用权) */ if( pxTCB == pxCurrentTCB ) { configASSERT( uxSchedulerSuspended == 0 ); portYIELD_WITHIN_API(); } else { mtCOVERAGE_TEST_MARKER(); } } }
#endif /* INCLUDE_vTaskDelete */
### 任务挂起

我们在源码中直接使用注释分析:
#if ( INCLUDE_vTaskSuspend == 1 )
void vTaskSuspend( TaskHandle_t xTaskToSuspend )
{
TCB_t \*pxTCB;
/\*
进入临界段 */ taskENTER_CRITICAL(); { /* If null is passed in here then it is the running task that is being suspended. 获取任务控制块 */ pxTCB = prvGetTCBFromHandle( xTaskToSuspend );
traceTASK\_SUSPEND( pxTCB );
/\* Remove task from the ready/delayed list and place in the
suspended list. 从就绪列表中删除 */ if( uxListRemove( &( pxTCB->xStateListItem ) ) == ( UBaseType_t ) 0 ) { taskRESET_READY_PRIORITY( pxTCB->uxPriority ); } else { mtCOVERAGE_TEST_MARKER(); }
/\* Is the task waiting on an event also?
从事件列表中移除 */ if( listLIST_ITEM_CONTAINER( &( pxTCB->xEventListItem ) ) != NULL ) { ( void ) uxListRemove( &( pxTCB->xEventListItem ) ); } else { mtCOVERAGE_TEST_MARKER(); } /* 把任务添加到挂起列表中 */ vListInsertEnd( &xSuspendedTaskList, &( pxTCB->xStateListItem ) );
#if( configUSE\_TASK\_NOTIFICATIONS == 1 )
{
if( pxTCB->ucNotifyState == taskWAITING_NOTIFICATION )
{
/\* The task was blocked to wait for a notification, but is
now suspended, so no notification was received. */ pxTCB->ucNotifyState = taskNOT_WAITING_NOTIFICATION; } } #endif } /* 退出临界段 */ taskEXIT_CRITICAL(); /* 判断调度器是否开始 看看是否有更高优先级的任务 */ if( xSchedulerRunning != pdFALSE ) { /* Reset the next expected unblock time in case it referred to the task that is now in the Suspended state. */ taskENTER_CRITICAL(); { prvResetNextTaskUnblockTime(); } taskEXIT_CRITICAL(); } else { mtCOVERAGE_TEST_MARKER(); }
if( pxTCB == pxCurrentTCB )
{
if( xSchedulerRunning != pdFALSE )
{
/\* The current task has just been suspended.
直接进行任务调度,释放CPU */ configASSERT( uxSchedulerSuspended == 0 ); portYIELD_WITHIN_API(); } else { /* The scheduler is not running, but the task that was pointed to by pxCurrentTCB has just been suspended and pxCurrentTCB must be adjusted to point to a different task. 调度器没有开启,pxCurrentTCB必须指向另外一个不同的task 因为这个任务被挂起了 */ if( listCURRENT_LIST_LENGTH( &xSuspendedTaskList ) == uxCurrentNumberOfTasks ) { /* No other tasks are ready, so set pxCurrentTCB back to NULL so when the next task is created pxCurrentTCB will be set to point to it no matter what its relative priority is. 没有任务准备,把当前的任务控制块复制为NULL */ pxCurrentTCB = NULL; } else { /*手动进行调度,在就绪列表中找到优先级最高的任务*/ vTaskSwitchContext(); } } } else { mtCOVERAGE_TEST_MARKER(); } }
#endif /* INCLUDE_vTaskSuspend */
### 任务恢复
我们在源码中直接使用注释分析:
#if ( INCLUDE_vTaskSuspend == 1 )
void vTaskResume( TaskHandle_t xTaskToResume )
{
/\*获取要恢复的任务控制块\*/
TCB_t \* const pxTCB = ( TCB_t \* ) xTaskToResume;
/\* It does not make sense to resume the calling task.
检查*/ configASSERT( xTaskToResume );
/\* The parameter cannot be NULL as it is impossible to resume the
收集整理了一份《2024年最新物联网嵌入式全套学习资料》,初衷也很简单,就是希望能够帮助到想自学提升的朋友。
一个人可以走的很快,但一群人才能走的更远!不论你是正从事IT行业的老鸟或是对IT行业感兴趣的新人
都欢迎加入我们的的圈子(技术交流、学习资源、职场吐槽、大厂内推、面试辅导),让我们一起学习成长!