FreeRTOS同步和互斥机制以及相关API
FreeRTOS 提供了多种 同步(Synchronization) 和 互斥(Mutex) 机制,以确保多任务环境下数据的安全访问和任务间的协调执行。以下是主要机制及其 API 的详细说明:
1. 互斥机制(Mutex)
用于保护共享资源,防止多个任务同时访问,避免数据竞争。
1.1 标准互斥量(Mutex)
- 特点:
- 支持 优先级继承(Priority Inheritance),防止优先级反转问题。
- 同一任务 不能 递归获取(重复获取会导致死锁)。
- API:
// 创建互斥量(初始状态为可用) SemaphoreHandle_t xSemaphoreCreateMutex(void); // 获取互斥量(阻塞) BaseType_t xSemaphoreTake(SemaphoreHandle_t xMutex, TickType_t xBlockTime); // 释放互斥量 BaseType_t xSemaphoreGive(SemaphoreHandle_t xMutex);
1.2 递归互斥量(Recursive Mutex)
- 特点:
- 允许 同一任务多次获取,必须对应相同次数的释放。
- 适用于函数递归调用或嵌套访问共享资源的情况。
- API:
// 创建递归互斥量 SemaphoreHandle_t xSemaphoreCreateRecursiveMutex(void); // 递归获取互斥量 BaseType_t xSemaphoreTakeRecursive(SemaphoreHandle_t xMutex, TickType_t xBlockTime); // 递归释放互斥量 BaseType_t xSemaphoreGiveRecursive(SemaphoreHandle_t xMutex