Files
CCU621M/app/app_init/task_lock.c
T

103 lines
2.9 KiB
C
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
#include "app_init/task_lock.h"
/**
* @brief 每任务锁句柄数组(外部可见)。
*
* @details
* - 下标与 `TASK_ID` 一一对应;
* - 每个任务默认预留一个 mutex;
* - 具体何时初始化由各任务自行调用 `u8_task_lock_ctrl(..., TASK_LOCK_OP_INIT)`。
*/
static SemaphoreHandle_t g_task_lock_handles[MY_TASK_NUM] = {0};
/**
* @brief 自定义锁句柄控制接口。
*
* @details
* 通过外部传入的 `SemaphoreHandle_t` 句柄指针执行统一锁操作:
* - INIT:若句柄为空则创建 mutex;
* - TAKE:阻塞获取 mutex
* - GIVE:释放 mutex
* - DELETE:删除 mutex 并清空句柄。
*
* @param p_handle 外部锁句柄地址。
* @param op 锁操作动作(初始化、上锁、解锁、删除)。
* @return uint8_t 1-成功,0-失败(指针非法/句柄为空/RTOS调用失败)。
*/
uint8_t u8_task_lock_handle_ctrl(SemaphoreHandle_t *p_handle, TASK_LOCK_OP_E op)
{
if (p_handle == NULL) {
return 0U;
}
switch (op) {
case TASK_LOCK_OP_INIT:
if (*p_handle == NULL) {
*p_handle = xSemaphoreCreateMutex();
}
return (*p_handle != NULL) ? 1U : 0U;
case TASK_LOCK_OP_TAKE:
if (*p_handle == NULL) {
return 0U;
}
return (xSemaphoreTake(*p_handle, portMAX_DELAY) == pdPASS) ? 1U : 0U;
case TASK_LOCK_OP_GIVE:
if (*p_handle == NULL) {
return 0U;
}
return (xSemaphoreGive(*p_handle) == pdTRUE) ? 1U : 0U;
case TASK_LOCK_OP_DELETE:
if (*p_handle != NULL) {
vSemaphoreDelete(*p_handle);
*p_handle = NULL;
}
return 1U;
default:
return 0U;
}
}
/**
* @brief 统一线程锁控制接口。
*
* @details
* 根据任务ID选择对应互斥锁句柄,并执行指定动作:
* - INIT:若未创建则创建 mutex
* - TAKE:阻塞获取 mutex
* - GIVE:释放 mutex
* - DELETE:删除 mutex 并清空句柄。
*
* @param task_id 任务ID`TASK_ID` 枚举,作为锁数组下标)。
* @param op 锁操作动作(初始化、上锁、解锁、删除)。
* @return uint8_t 1-成功,0-失败(ID非法/句柄为空/RTOS调用失败)。
*/
uint8_t u8_task_lock_ctrl(TASK_ID task_id, TASK_LOCK_OP_E op)
{
uint8_t id = (uint8_t)task_id;
if (id >= (uint8_t)MY_TASK_NUM) {
return 0U;
}
switch (op) {
case TASK_LOCK_OP_INIT:
return u8_task_lock_handle_ctrl(&g_task_lock_handles[id], TASK_LOCK_OP_INIT);
case TASK_LOCK_OP_TAKE:
return u8_task_lock_handle_ctrl(&g_task_lock_handles[id], TASK_LOCK_OP_TAKE);
case TASK_LOCK_OP_GIVE:
return u8_task_lock_handle_ctrl(&g_task_lock_handles[id], TASK_LOCK_OP_GIVE);
case TASK_LOCK_OP_DELETE:
return u8_task_lock_handle_ctrl(&g_task_lock_handles[id], TASK_LOCK_OP_DELETE);
default:
return 0U;
}
}