freertos 关中断和临界区的关系

freertos 临界区 和关中断

基础概念:
临界区:保证一段代码操作的原子性。原子性:即一段代码不能被打断运行,直到退出改代码段。用于保证资源变量被多个线程或代码段访问时产生的冲突。
**实现:**在单核系统中,可以使用关中断来实现原子操作。

freertos中的实现:

进入临界区


#define portDISABLE_INTERRUPTS()				vPortRaiseBASEPRI()
#define portENABLE_INTERRUPTS()					vPortSetBASEPRI( 0 )
void vPortEnterCritical( void )
{
	portDISABLE_INTERRUPTS();
	uxCriticalNesting++;

	/* This is not the interrupt safe version of the enter critical function so
	assert() if it is being called from an interrupt context.  Only API
	functions that end in "FromISR" can be used in an interrupt.  Only assert if
	the critical nesting count is 1 to protect against recursive calls if the
	assert function also uses a critical section. */
	if( uxCriticalNesting == 1 )
	{
		configASSERT( ( portNVIC_INT_CTRL_REG & portVECTACTIVE_MASK ) == 0 );
	}
}

退出临界区

void vPortExitCritical( void )
{
	configASSERT( uxCriticalNesting );
	uxCriticalNesting--;
	if( uxCriticalNesting == 0 )
	{
		portENABLE_INTERRUPTS();
	}
}

ARM cortex M3/4 的关中断操作:

static portFORCE_INLINE void vPortSetBASEPRI( uint32_t ulBASEPRI )
{
	__asm
	{
		/* Barrier instructions are not used as this function is only used to
		lower the BASEPRI value. */
		msr basepri, ulBASEPRI
	}
}
/*-----------------------------------------------------------*/

static portFORCE_INLINE void vPortRaiseBASEPRI( void )
{
uint32_t ulNewBASEPRI = configMAX_SYSCALL_INTERRUPT_PRIORITY;

	__asm
	{
		/* Set BASEPRI to the max syscall priority to effect a critical
		section. */
		msr basepri, ulNewBASEPRI
		dsb
		isb
	}
}

宏解释:

1、configMAX_SYSCALL_INTERRUPT_PRIORITY:最大系统调用优先级。即xxx_from_isr 系统调用可以用于 优先级数值大于configMAX_SYSCALL_INTERRUPT_PRIORITY的中断。即较低优先级的中断(数值大于)可以使用 xxx_from_isr 系统调用。

因为优先级数值大于configMAX_SYSCALL_INTERRUPT_PRIORITY的中断进入临界区会被禁止,因此哪些中断优先级较低的优先级可以通过系统调用接口xxx_from_isr访问内核,因为这些中断不会和内核临界区同时运行。
而,优先级数值低于configMAX_SYSCALL_INTERRUPT_PRIORITY中断,优先级较高的中断,不会被内核进入临界区静止,因此,这些高优先级的中断里面,一定不能使用系统调用接口。不然会造成临界区失效,内核混乱。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值