FreeRTOS Mutex 意外行为

如何解决FreeRTOS Mutex 意外行为

#include "main.h"
#include "FreeRTOS.h"
#include "semphr.h"
#include "task.h"

/* Private function prototypes -----------------------------------------------*/
void SystemClock_Config(void);
static void MX_GPIO_Init(void);
static void MX_USART2_UART_Init(void);
void Task1(void *argument);
void Task2(void *argument);
void PrintMsg(char *data);
/* USER CODE BEGIN PFP */

SemaphoreHandle_t hMutex = NULL;
TaskHandle_t hTask1 = NULL;
TaskHandle_t hTask2 = NULL;
UART_HandleTypeDef huart2;

int main(void) {
    /* MCU Configuration--------------------------------------------------------*/
    /* Reset of all peripherals,Initializes the Flash interface and the Systick. */
    HAL_Init();
    /* Configure the system clock */
    SystemClock_Config();
    /* Initialize all configured peripherals */
    MX_GPIO_Init();
    MX_USART2_UART_Init();

    /* USER CODE BEGIN 2 */
    xTaskCreate(Task1,"Task 1",configMINIMAL_STACK_SIZE,NULL,2,&hTask1);
    xTaskCreate(Task2,"Task 2",&hTask2);
    /* USER CODE END 2 */

    hMutex = xSemaphoreCreateMutex();
    if (hMutex == NULL) {
        PrintMsg("Mutex not created\r\n");
    } else {
        PrintMsg("Mutex created\r\n");
    }

    vTaskStartScheduler();

    /* USER CODE BEGIN WHILE */
    while (1) {
        /* USER CODE END WHILE */
        /* USER CODE BEGIN 3 */
    }
    /* USER CODE END 3 */
}


void Task1(void *argument) {
    /* USER CODE BEGIN 5 */
    /* Infinite loop */
    for (;;) {
        if (xSemaphoreTake(hMutex,2000) == pdTRUE) {
            PrintMsg("Shared Resource Start and Executing Task 1\r\n");
            xSemaphoreGive(hMutex);
            PrintMsg("Shared Resource End and Executing Task 1\r\n");
            vTaskDelay(100);
        } else {
            PrintMsg("Task 1 Didn't get access to shared resource\r\n");
        }
    }
    /* USER CODE END 5 */
}


void Task2(void *argument) {
    /* USER CODE BEGIN 5 */
    /* Infinite loop */
    for (;;) {
        if (xSemaphoreTake(hMutex,2000) == pdTRUE) {
            PrintMsg("Shared Resource Start and Executing Task 2\r\n");
            //xSemaphoreGive(hMutex);
            PrintMsg("Shared Resource End and Executing Task 2\r\n");
            vTaskDelay(100);
        } else {
            PrintMsg("Task 2 Didn't get access to shared resource\r\n");
        }
    }
    /* USER CODE END 5 */
}


void PrintMsg(char *data) {
    int i = 0;
    while (*(data + i) != '\0') {
        HAL_UART_Transmit(&huart2,(uint8_t*) &data[i],1,0xFF);
        i++;
    }
}

使用的硬件:STM32F446RE

当我运行这段代码时,我得到如下输出

//输出开始

创建互斥锁

共享资源启动并执行任务1

共享资源结束并执行任务1

任务 2 无法访问共享资源

Task 1 DiTask 2 无法访问共享资源

任务 1 无法访问共享资源

任务 2 无法访问共享资源 . .

//输出结束

问题 1)

考虑到 Task1 被首先调度,因为 Task1 和 2 的优先级相同。 Task1 执行正确。

在此之后,Task2 已安排但无法获取互斥锁,因此我得到的输出为“Task 2 无法访问共享资源”。为什么会这样?

问题 2 )

“Task 1 DiTask 2 did not get access to shared resource”在这一行中,似乎 Task1 正在执行但它被 Task2 抢占,这本不应该发生,因为两个任务具有相同的优先级??

解决方法

问题 1:这里可能的解释是,您被相互竞争的任务覆盖了彼此缓冲的 UART 输出所愚弄。 UART 慢,任务切换快 :)

Task1 打印“Shared Resource Start and Executing Task 1”并第一次释放互斥锁后,scheduler 立即切换到Task2(可能是因为Task1 已经用完了它的时间槽?)。 Task2 获取互斥锁,快速将它的两个消息都吐到 UART 缓冲区中,然后进入睡眠状态 100 个滴答声。调度程序立即切换回 Task1,但不幸的是,来自 Task2 的缓冲消息尚未到达 UART 输出。在打印单个字节的 Task2-s 消息之前,UART 缓冲区被消息“Shared Resource End and Executing Task 1”覆盖。

之后整个过程停止,因为您还没有释放 Task2 中的互斥锁。

Q2:当调度器决定时(通常是当它们进入睡眠或用完它们的时间段时),具有相同优先级的任务会被彼此抢占

我会推荐这本tutorial/book,第 3 章对任务的工作原理有很好的解释。

,

USART 是一个资源,所以它不能被没有同步机制的两个任务共享,比如互斥锁。您对 PrintMsg() 的使用违反了此规则。

调度程序以 configTICK_RATE_HZ 频率运行。如果 configUSE_TIME_SLICING1(或未定义),调度程序会在同等优先级的任务之间切换。如果您不想要这种默认行为,请将 configUSE_TIME_SLICING 设置为 0

请记住,您的 configTICK_RATE_HZ 设置 1000 最多可为每个任务提供约 1 毫秒的运行时间,除非没有其他任务可以运行。更高优先级的任务也可以在 1 毫秒过去之前抢占它。使用 115200 波特率,您可以在这个 ~1 毫秒的时间段内发送 ~10 个字节左右。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams['font.sans-serif'] = ['SimHei'] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -> systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping("/hires") public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate<String
使用vite构建项目报错 C:\Users\ychen\work>npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-
参考1 参考2 解决方案 # 点击安装源 协议选择 http:// 路径填写 mirrors.aliyun.com/centos/8.3.2011/BaseOS/x86_64/os URL类型 软件库URL 其他路径 # 版本 7 mirrors.aliyun.com/centos/7/os/x86
报错1 [root@slave1 data_mocker]# kafka-console-consumer.sh --bootstrap-server slave1:9092 --topic topic_db [2023-12-19 18:31:12,770] WARN [Consumer clie
错误1 # 重写数据 hive (edu)> insert overwrite table dwd_trade_cart_add_inc > select data.id, > data.user_id, > data.course_id, > date_format(
错误1 hive (edu)> insert into huanhuan values(1,'haoge'); Query ID = root_20240110071417_fe1517ad-3607-41f4-bdcf-d00b98ac443e Total jobs = 1
报错1:执行到如下就不执行了,没有显示Successfully registered new MBean. [root@slave1 bin]# /usr/local/software/flume-1.9.0/bin/flume-ng agent -n a1 -c /usr/local/softwa
虚拟及没有启动任何服务器查看jps会显示jps,如果没有显示任何东西 [root@slave2 ~]# jps 9647 Jps 解决方案 # 进入/tmp查看 [root@slave1 dfs]# cd /tmp [root@slave1 tmp]# ll 总用量 48 drwxr-xr-x. 2
报错1 hive> show databases; OK Failed with exception java.io.IOException:java.lang.RuntimeException: Error in configuring object Time taken: 0.474 se
报错1 [root@localhost ~]# vim -bash: vim: 未找到命令 安装vim yum -y install vim* # 查看是否安装成功 [root@hadoop01 hadoop]# rpm -qa |grep vim vim-X11-7.4.629-8.el7_9.x
修改hadoop配置 vi /usr/local/software/hadoop-2.9.2/etc/hadoop/yarn-site.xml # 添加如下 <configuration> <property> <name>yarn.nodemanager.res