- 有时候删除任务是很有必要的。删除任务,是说任务将返回并处于休眠状态(参看3.02,任务状态),并不是说任务的代码被删除了,只是任务的代码不再被µC/OS-Ⅱ调用。通过调用OSTaskDel()就可以完成删除任务的功能(如程序清单 L4.11所示)。OSTaskDel()一开始应确保用户所要删除的任务并非是空闲任务,因为删除空闲任务是不允许的[L4.11(1)]。不过,用户可以删除statistic任务[L4.11(2)]。接着,OSTaskDel()还应确保用户不是在ISR例程中去试图删除一个任务,因为这也是不被允许的[L4.11(3)]。调用此函数的任务可以通过指定OS_PRIO_SELF参数来删除自己[L4.11(4)]。接下来OSTaskDel()会保证被删除的任务是确实存在的[L4.11(3)]。如果指定的参数是OS_PRIO_SELF的话,这一判断过程(任务是否存在)自然是可以通过的,但笔者不准备为这种情况单独写一段代码,因为这样只会增加代码并延长程序的执行时间。程序清单 L 4.11 删除任务
- INT8U OSTaskDel (INT8U prio)
- {
- OS_TCB *ptcb;
- OS_EVENT *pevent;
- if (prio == OS_IDLE_PRIO) { (1)
- return (OS_TASK_DEL_IDLE);
- }
- if (prio >= OS_LOWEST_PRIO && prio != OS_PRIO_SELF) { (2)
- return (OS_PRIO_INVALID);
- }
- OS_ENTER_CRITICAL();
- if (OSIntNesting > 0) { (3)
- OS_EXIT_CRITICAL();
- return (OS_TASK_DEL_ISR);
- }
- if (prio == OS_PRIO_SELF) { (4)
- Prio = OSTCBCur->OSTCBPrio;
- }
- if ((ptcb = OSTCBPrioTbl[prio]) != (OS_TCB *)0) { (5)
- if ((OSRdyTbl[ptcb->OSTCBY] &= ~ptcb->OSTCBBitX) == 0) { (6)
- OSRdyGrp &= ~ptcb->OSTCBBitY;
- }
- if ((pevent = ptcb->OSTCBEventPtr) != (OS_EVENT *)0) { (7)
- if ((pevent->OSEventTbl[ptcb->OSTCBY] &= ~ptcb->OSTCBBitX) == 0) {
- pevent->OSEventGrp &= ~ptcb->OSTCBBitY;
- }
- }
- Ptcb->OSTCBDly = 0; (8)
- Ptcb->OSTCBStat = OS_STAT_RDY; (9)
- OSLockNesting++; (10)
- OS_EXIT_CRITICAL(); (11)
- OSDummy(); (12) OS_ENTER_CRITICAL();
- OSLockNesting--; (13)
- OSTaskDelHook(ptcb); (14)
- OSTaskCtr--;
- OSTCBPrioTbl[prio] = (OS_TCB *)0; (15)
- if (ptcb->OSTCBPrev == (OS_TCB *)0) { (16)
- ptcb->OSTCBNext->OSTCBPrev = (OS_TCB *)0;
- OSTCBList = ptcb->OSTCBNext;
- } else {
- ptcb->OSTCBPrev->OSTCBNext = ptcb->OSTCBNext;
- ptcb->OSTCBNext->OSTCBPrev = ptcb->OSTCBPrev;
- }
- ptcb->OSTCBNext = OSTCBFreeList; (17)
- OSTCBFreeList = ptcb;
- OS_EXIT_CRITICAL();
- OSSched(); (18)
- return (OS_NO_ERR);
- } else {
- OS_EXIT_CRITICAL();
- return (OS_TASK_DEL_ERR);
- }
- }
删除任务
最新推荐文章于 2022-11-15 15:11:39 发布