os_enter_critical
所属模块:内核机制 | 类型:临界区控制函数
函数简介
os_enter_critical 用于进入临界区,通过关闭中断保护关键代码执行过程,
防止任务切换或中断打断当前操作。
该机制用于保护共享资源访问,是内核并发控制的重要基础。
函数原型
void os_enter_critical(void);
源码实现
/*------------------------------------------------------------------------
| FILE DESCRIPTION |
------------------------------------------------------------------------*/
/*------------------------------------------------------------------------
| - File name : enter_critical.c
| - Author : 谭舒
| - Update date : 2026-09-19
| - Copyright(C) : 2026 HRTOS. All rights reserved.
------------------------------------------------------------------------*/
/*------------------------------------------------------------------------
| INCLUDES |
------------------------------------------------------------------------*/
#include"hrtos_internal.h"
/*------------------------------------------------------------------------
| API FUNCTIONS |
------------------------------------------------------------------------*/
/**
* @brief 进入临界区,禁止中断打断当前代码执行。
*
* @param[in] None
*
* @return None。
*
* @note 支持临界区嵌套。
* 第一次进入临界区时保存当前中断使能状态,并关闭中断。
* 后续嵌套进入临界区时仅增加临界区嵌套计数。
* 应与 os_exit_critical() 配对使用。
*/
void os_enter_critical()//关中断,保护运行不被打断
{
if(os_critical_nesting == 0)
{
os_int_status = EA;
EA = 0;
}
os_critical_nesting++;
}
/*------------------------------------------------------------------------
| END OF FILE: enter_critical.c |
------------------------------------------------------------------------*/
使用示例
void task()
{
os_enter_critical();
// 访问共享资源
shared_data++;
os_exit_critical();
}
注意事项
临界区必须成对使用(enter / exit),否则可能导致系统中断永久关闭。