
下图是执行结果。

如果我将OSTimeDly(100);替换成for(;;)那么这个2个任务只有一个可以运行了。原因就是OSTimeDly(100);函数。我们看看OSTimeDly(100);的说明
- //将一个任务延时若干个时钟节拍
- //描述:将一个任务延时若干个时钟节拍。如果延时时间大于0,系统将立即进行任务调度。延时时间的长度
- // 可从0到65535个时钟节拍。延时时间0表示不进行延时,函数将立即返回调用者。延时的具体时间依
- // 赖于系统每秒钟有多少时钟节拍(由文件OS_CFG.H中的常量OS_TICKS_PER_SEC设定)
- //
- //附加:调用该函数会使uCOS-II进行一次任务调度,并且执行下一个优先级最高的就绪态任务。任务调用
- // OSTimeDly()后,一旦规定的时间期满或者有其它的任务通过调用OSTimeDlyResume()取消了延时,
- // 它就会马上进入就绪状态。注意,只有当该任务在所有就绪任务中具有最高的优先级时,它才会立即
- // 运行。
- //
- //参数:ticks 为要延时的时钟节拍数。(一个1到65535之间的数)
- //
- //注意:注意到延时时间0表示不进行延时操作,而立即返回调用者,为了确保设定的延时时间,建议用户设定
- // 的时钟节拍数加1。例如,希望延时10个时钟节拍,可设定参数为11。
- //
- //任务延时函数(时钟节拍数)
- void OSTimeDly (INT16U ticks)
- {
- #if OS_CRITICAL_METHOD == 3 //中断函数被设定为模式3
- OS_CPU_SR cpu_sr;
- #endif
- if (ticks > 0) { //如果延时设定为0值,表示不想对任务延时,返回调用任务
- OS_ENTER_CRITICAL(); //关闭中断
- if ((OSRdyTbl[OSTCBCur->OSTCBY] &= ~OSTCBCur->OSTCBBitX) == 0) { /* Delay current task */
- OSRdyGrp &= ~OSTCBCur->OSTCBBitY;
- }
- //非0值会使得任务延时函数OSTimeDly()将当前任务从就绪表中移除
- OSTCBCur->OSTCBDly = ticks; //接着,这个延时节拍数会被保存在当前任务的OS_TCB中
- OS_EXIT_CRITICAL(); //打开中断
- OS_Sched(); //既然任务已经不再处于就绪任务,(任务调度),任务调度程序会执行下一个优先级最高的就绪任务
- }
- }
/*
*********************************************************************************************************
* DELAY TASK 'n' TICKS
*
* Description: This function is called to delay execution of the currently running task until the
* specified number of system ticks expires. This, of course, directly equates to delaying
* the current task for some time to expire. No delay will result If the specified delay is
* 0. If the specified delay is greater than 0 then, a context switch will result.
*
* Arguments : ticks is the time delay that the task will be suspended in number of clock 'ticks'.
* Note that by specifying 0, the task will not be delayed.
*
* Returns : none
*********************************************************************************************************
*/
void OSTimeDly (INT32U ticks)
{
INT8U y;
#if OS_CRITICAL_METHOD == 3u /* Allocate storage for CPU status register */
OS_CPU_SR cpu_sr = 0u;
#endif
if (OSIntNesting > 0u) { /* See if trying to call from an ISR */
return;
}
if (OSLockNesting > 0u) { /* See if called with scheduler locked */
return;
}
if (ticks > 0u) { /* 0 means no delay! */
OS_ENTER_CRITICAL();
y = OSTCBCur->OSTCBY; /* Delay current task */
OSRdyTbl[y] &= (OS_PRIO)~OSTCBCur->OSTCBBitX;
if (OSRdyTbl[y] == 0u) {
OSRdyGrp &= (OS_PRIO)~OSTCBCur->OSTCBBitY;
}
OSTCBCur->OSTCBDly = ticks; /* Load ticks in TCB */
OS_EXIT_CRITICAL();
OS_Sched(); /* Find next task to run! */
}
}
不多说了,就是OSTimeDly (100);可以使得当前任务进入到挂起状态,然后执行一次任务调度,然后执行下一个优先级最高的就绪任务,这样就使得2个任务可以交替进行了。
如果将OSTimeDly (100);替换为for(;;)该任务就无法挂起,另外一个任务就无法得到执行。如下图,我将任务2的延时换成了for(j=0;j<99999999;j++);执行结果如下。
可以看到一旦任务2得到执行,它会一直占用CPU,即使它的优先级只是6,低于任务1的优先级5。
