分类: 嵌入式
2014-12-14 11:28:21
移植UCOSII的时发现程序在运行一段时间后出现跑飞现象,后来发现是程序在进出中断的时候没有进行临界状态保护。加入临界状态保护后程序变的稳定,没有出现飞现象。
临界状态保护程序如下:
#if OS_CRITICAL_METHOD == 3
OS_CPU_SR cpu_sr = 0;
#endif
OS_ENTER_CRITICAL();
OSIntNesting++;
OS_EXIT_CRITICAL();
{
// ISR();
}
OSIntExit();
其中 ISR(); 是用户中断服务程序。
对如上程序解释如下:
一、#if OS_CRITICAL_METHOD == 3
Method #1: Disable/Enable interrupts using simple instructions. After critical section,interrupts will be enabled even if they were disabled before entering the critical section.
Method #2: Disable/Enable interrupts by preserving the state of interrupts. In other words, if interrupts were disabled before entering the critical section, they will be disabled when leaving the critical section.
Method #3: Disable/Enable interrupts by preserving the state of interrupts. Generally speaking you would store the state of the interrupt disable flag in the local variable 'cpu_sr' and then disable interrupts. 'cpu_sr' is allocated in all of uC/OS-II's s that need to disable interrupts. You would restore the interrupt disable state by copying back 'cpu_sr' into the CPU's status register
根据UCOSII中提示:
(1)、当OS_CRITICAL_METHOD为1时,无论调用critical section之前是否开中断,在退出后中断将使能。这样的话把本身不需要的中断也将打开,这是我们所不希望看到的。
(2)、当OS_CRITICAL_METHOD为2时,在进入critical section之前对中断状态进行压栈,当从critical section退出的时候并不改变中断的状态。
(3)、将处理器状态字保存在局部变量cpu_sr中,也就是说先保存原来的中断状态到cpu_sr,然后再关闭中断。
二、OS_CPU_SR cpu_sr = 0;
声明了一个unsigned int类型的局部变量,用来存放中断状态。
三、OSIntNesting是中断嵌套层数的变量,ucossii通过这个全局变量确保在中断嵌套的时候不进行任务调度。
四、OSIntExit(),在此函数中先进行OSintNesting减1,然后判断是否有中断嵌套,如果没有的话就退出中断进行任务调度。