FreeRTOS连载07:优先级继承 - 解决优先级反转问题的算法实现

FreeRTOS 任务优先级 【杂记】 特别注意:IRQ 任务和高优先级任务必须设置为阻塞式(调用消息等待或者延迟等函数即可),只有这样,高优先级任务才会释放 CPU 的使用权,,从而低优先级任务才有机会得到执行。无论何时中断的优先级都是最高的,中断的优先级永远高于任何任务的优先级,即任务在执行的过程中,中断来了就开始执行中断服务程序。IRQ 任务:IRQ 任务是指通过中断服务程序进行触发的任务,此类任务应该设置为所有任务里面优先级最高的。0为最高,15为最低。2、用户配置任务的优先级数值越小,那么此任务的优先级越低,空闲任务的优先级是 0。 阅读详情

引言

优先级反转是实时系统中的经典问题,它可能导致高优先级任务被低优先级任务阻塞,严重影响系统的实时性。FreeRTOS通过优先级继承机制巧妙地解决了这个问题。本文将深入分析FreeRTOS V11.1.0中优先级继承的实现原理和应用技巧。

1. 优先级反转问题

1.1 什么是优先级反转

优先级反转是指高优先级任务被低优先级任务间接阻塞的现象。典型场景:

任务优先级:TaskH (高) > TaskM (中) > TaskL (低)
​
时间线:
1. TaskL获得互斥量,开始执行
2. TaskH需要该互斥量,被阻塞
3. TaskM抢占TaskL,开始执行
4. TaskH被TaskM间接阻塞,优先级反转发生

1.2 优先级反转的危害

/* 优先级反转示例 */
SemaphoreHandle_t xMutex;
​
/* 低优先级任务 */
void vLowPriorityTask( void *pvParameters )
{
    for( ;; )
    {
        /* 获取互斥量 */
        if( xSemaphoreTake( xMutex, portMAX_DELAY ) == pdTRUE )
        {
            printf( "Low priority task: Got mutex\r\n" );
            
            /* 长时间持有互斥量 */
            vTaskDelay( pdMS_TO_TICKS( 1000 ) );
            
            printf( "Low priority task: Releasing mutex\r\n" );
            xSemaphoreGive( xMutex );
        }
        
        vTaskDelay( pdMS_TO_TICKS( 2000 ) );
    }
}
​
/* 中优先级任务 */
void vMediumPriorityTask( void *pvParameters )
{
    for( ;; )
    {
        printf( "Medium priority task: Running\r\n" );
        
        /* CPU密集型工作,抢占低优先级任务 */
        volatile uint32_t i;
        for( i = 0; i < 10000000; i++ );
        
        vTaskDelay( pdMS_TO_TICKS( 500 ) );
    }
}
​
/* 高优先级任务 */
void vHighPriorityTask( void *pvParameters )
{
    for( ;; )
    {
        vTaskDelay( pdMS_TO_TICKS( 3000 ) );
        
        printf( "High priority task: Trying to get mutex\r\n" );
        
        /* 尝试获取互斥量,可能被低优先级任务阻塞 */
        if( xSemaphoreTake( xMutex, pdMS_TO_TICKS( 5000 ) ) == pdTRUE )
        {
            printf( "High priority task: Got mutex\r\n" );
            
            /* 关键操作 */
            vTaskDelay( pdMS_TO_TICKS( 100 ) );
            
            xSemaphoreGive( xMutex );
            printf( "High priority task: Released mutex\r\n" );
        }
        else
        {
            printf( "High priority task: Timeout waiting for mutex!\r\n" );
        }
    }
}

2. 优先级继承机制

2.1 优先级继承原理

当高优先级任务被互斥量阻塞时,持有互斥量的低优先级任务临时继承高优先级任务的优先级:

/* TCB中的优先级字段 */
typedef struct tskTaskControlBlock
{
    UBaseType_t uxPriority;        /* 当前优先级 */
    UBaseType_t uxBasePriority;    /* 基础优先级 */
    UBaseType_t uxMutexesHeld;     /* 持有的互斥量数量 */
    /* ... 其他字段 ... */
} tskTCB;
​
/* 优先级继承的核心思想 */
/*
 * 1. uxBasePriority:任务的原始优先级,不会改变
 * 2. uxPriority:任务的当前优先级,可能因继承而提升
 * 3. 当任务释放所有互斥量时,优先级恢复到uxBasePriority
 */

2.2 互斥量结构设计

/* 互斥量的内部结构(基于队列实现) */
typedef struct QueueDefinition
{
    int8_t *pcHead;                    /* 队列头指针 */
    int8_t *pcWriteTo;                 /* 写入位置 */
    
    union
    {
        QueuePointers_t xQueue;        /* 队列指针 */
        SemaphoreData_t xSemaphore;    /* 信号量数据 */
    } u;
    
    List_t xTasksWaitingToSend;        /* 等待发送的任务链表 */
    List_t xTasksWaitingToReceive;     /* 等待接收的任务链表 */
    
    volatile UBaseType_t uxMessagesWaiting; /* 队列中的消息数 */
    UBaseType_t uxLength;              /* 队列长度 */
    UBaseType_t uxItemSize;            /* 项目大小 */
    
    volatile int8_t cRxLock;           /* 接收锁 */
    volatile int8_t cTxLock;           /* 发送锁 */
    
    #if ( ( configSUPPORT_STATIC_ALLOCATION == 1 ) && ( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) )
        uint8_t ucStaticallyAllocated; /* 静态分配标志 */
    #endif
    
    #if ( configUSE_QUEUE_SETS == 1 )
        struct QueueDefinition *pxQueueSetContainer;
    #endif
    
    #if ( configUSE_TRACE_FACILITY == 1 )
        UBaseType_t uxQueueNumber;
        uint8_t ucQueueType;
    #endif
} xQUEUE;
​
/* 信号量数据结构 */
typedef struct SemaphoreData
{
    TaskHandle_t xMutexHolder;         /* 互斥量持有者 */
    UBaseType_t uxRecursiveCallCount;  /* 递归调用计数 */
} SemaphoreData_t;
```#
# 3. 优先级继承实现机制
​
### 3.1 互斥量获取时的优先级继承
​
```c
/* 互斥量获取函数 */
BaseType_t xQueueSemaphoreTake( QueueHandle_t xQueue, TickType_t xTicksToWait )
{
    BaseType_t xEntryTimeSet = pdFALSE;
    TimeOut_t xTimeOut;
    Queue_t * const pxQueue = xQueue;
​
    for( ;; )
    {
        taskENTER_CRITICAL();
        {
            /* 检查互斥量是否可用 */
            if( pxQueue->uxMessagesWaiting == ( UBaseType_t ) 0U )
            {
                /* 互斥量不可用,检查是否需要优先级继承 */
                if( pxQueue->u.xSemaphore.xMutexHolder != NULL )
                {
                    /* 实施优先级继承 */
                    if( pxQueue->u.xSemaphore.xMutexHolder->uxPriority < pxCurrentTCB->uxPriority )
                    {
                        vTaskPriorityInherit( pxQueue->u.xSemaphore.xMutexHolder );
                    }
                }
            }
            else
            {
                /* 互斥量可用,获取成功 */
                pxQueue->uxMessagesWaiting = 0U;
                pxQueue->u.xSemaphore.xMutexHolder = pxCurrentTCB;
                pxCurrentTCB->uxMutexesHeld++;
                
                taskEXIT_CRITICAL();
                return pdPASS;
            }
        }
        taskEXIT_CRITICAL();
​
        /* 互斥量不可用,需要等待 */
        if( xTicksToWait == ( TickType_t ) 0 )
        {
            return errQUEUE_EMPTY;
        }
        
        /* 设置超时并阻塞等待 */
        if( xEntryTimeSet == pdFALSE )
        {
            vTaskInternalSetTimeOutState( &xTimeOut );
            xEntryTimeSet = pdTRUE;
        }
        
        vTaskSuspendAll();
        prvLockQueue( pxQueue );
        
        if( xTaskCheckForTimeOut( &xTimeOut, &xTicksToWait ) == pdFALSE )
        {
            if( prvIsQueueEmpty( pxQueue ) != pdFALSE )
            {
                /*
【花雕学编程】Arduino FreeRTOS 之任务优先级继承 Arduino FreeRTOS 的任务优先级继承机制为解决优先级反转问题提供了一种有效的解决方案,具有简化开发、动态优先级调整和高兼容性等特点,广泛应用于嵌入式系统、工业自动化和机器人控制等领域。5、创新:Arduino可以让你用电子的方式来表达你的创意和想象,你可以用Arduino来制作各种有趣和有用的项目,如机器人、智能家居、艺术装置等。如果一个低优先级任务持有信号量并且高优先级任务需要这个信号量时,低优先级任务的优先级会临时提升到高优先级任务的优先级,以防止优先级反转的问题。 阅读详情

相关推荐

【Freertos基础入门】freertos任务的优先级

本系列基于stm32系列单片机来使用freerots任务管理是实时操作系统(RTOS)的核心功能之一,它允许开发者以并发的方式组织和管理多个任务。FreeRTOS 是一个流行的开源RTOS,它提供了强大的任务管理功能,让开发者能够轻松创建和控制任务。本文将介绍 FreeRTOS 的任务管理功能,包括任务的创建、删除、挂起、恢复和优先级控制等方面的内容。任务管理是 FreeRTOS 提供的一个强大功能,它允许开发者以并发的方式组织和管理多个任务。

m0_62599305的博客 8083

Codex登录要手机验证码?Cockpit Tools跳过验证保姆级教程

摘要:OpenAI升级风控后,Codex登录需手机验证,增加批量账号使用成本。CockpitTools(GitHub 8.3k star)可绕过验证,支持多AI编程平台账号管理。操作步骤:1) 获取ChatGPT网页Session数据;2) 通过转换工具生成CPA格式JSON;3) 导入工具启动Codex。注意:仅适用于未绑定手机号的账号,Session会过期,且需防范数据泄露风险。商业账号通常直接提供认证文件。(150字)

5893

开关电源PCB安规设计避坑指南:从光耦开槽到变压器挡墙,这些细节决定认证成败

本文深入解析开关电源PCB安规设计中的关键细节,包括光耦开槽、变压器挡墙工艺等12个致命要点。通过实际案例和工艺参数表,揭示如何避免认证失败,特别强调爬电距离和电气间隙的精确控制,助力工程师提升产品安全性和认证通过率。

weixin_42548893的博客 205

戴尔G3/AWCC用户必看:揪出WMI Provider Host疯狂占用的元凶,附5.4.35旧版回退保姆级教程

本文针对戴尔G3/AWCC用户遇到的WMI Provider Host异常占用问题,提供了详细的诊断方法和解决方案。通过分析AWCC 5.5.14.0版本的资源占用问题,指导用户回退到稳定版AWCC 5.4.35,并附上保姆级教程和预防措施,帮助用户彻底解决系统卡顿问题。

weixin_30892037的博客 563

PHP 对接建行生活订单推送接口

php对接建行订单推送

qq_43647026的博客 562

深入解析Unity3D中PostLateUpdate突然占用大量时间的原因

在Unity3D的生命周期中,是一个在LateUpdate之后被调用的方法。它通常用于处理一些需要在所有更新(包括物理更新和动画更新)之后进行的逻辑。由于它在游戏循环的后期阶段被调用,因此它通常用于处理与渲染直接相关的任务,如相机调整、UI更新等。突然占用大量时间的问题可能由多种原因引起,包括复杂的逻辑处理、频繁的资源加载、不恰当的渲染优化、插件或第三方库的副作用以及内存泄漏或垃圾回收等。为了解决这个问题,开发者需要仔细审查和优化中的代码,同时利用Unity提供的工具来监控和分析游戏性能。

Yori_22的博客 982

别再为格式发愁:safetensors转GGUF的三种高效方法及Ollama集成对比

本文详细介绍了将safetensors格式转换为GGUF格式的三种高效方法,包括llama.cpp原生转换、GGUF官方工具链和Transformers中转方案,并对比了它们在Ollama集成中的表现。文章还提供了实际项目中的踩坑经验和性能调优建议,帮助开发者快速掌握模型转换技术。

weixin_42651281的博客 641

Deep SHAP 深度学习模型的可解释性分析

Deep SHAP 算法是一种用于解释深度学习模型的技术, 该算法通过将每个特征的重要性与输出值相关联来进行解释。本博客对深度学习的模型可解释性进行了分析。

cnjs1994的博客 5121

基于四旋翼模型的火箭型无人机视线角保持控制仿真设计

本文针对火箭型无人机的视线角保持控制问题展开研究。基于四旋翼动力学模型,通过改造设计了一种摄像头朝上安装的特殊无人机系统,用于追踪空中目标。文章详细推导了坐标系定义、运动学和动力学方程,重点分析了摄像头安装与视线几何关系,建立了目标运动模型和视线向量计算方法。通过解算期望姿态角,实现了使机体Z轴始终对准目标的控制目标。仿真结果表明,该系统能有效完成视线角保持任务,为空对空监视等应用场景提供了可行方案。~~~~~

huanghm88的专栏 143

OV9734 DATASHEET,完整规格书

OV9734完整规格书,包括电气参数,尺寸规格,寄存器配置表等

老版QQ原生表情gif动态

这是老版的QQ表情,不过全是动态的的,Windows照片查看器是不会动的,可以右击用浏览器打开查看,再说一遍是老版的,只是分享给宁愿用老版也要动态的人。

VB摄像头监控

该VB模块可对摄像头捕获的画面进行录像等,可在创建的窗口进行控制

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

上一篇: FreeRTOS连载06:上下文切换机制 - 从汇编代码看任务切换的底层实现
下一篇: FreeRTOS连载09:队列机制深度解析 - 从环形缓冲区到生产者消费者模式
VehSwHwDeveloper
博客等级 码龄1年 457粉丝 217原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

VehSwHwDeveloper

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值