因為我利用一個排序的鏈表來保存就緒列表,所以調度程序容易實現。它只是檢測正在運行的任務與最高優先級的就緒任務是否是一個任務和同樣的優先級。如果是,調度任務完成。否則,它會啟動一個從前者到后者的設備場景的切換。這里是用C++實現的代碼。
/**************************************************************
*
* Method : schedule()
*
* Description : Select a new task to be run.
*
* Notes : If this routine is called from within an ISR, the
* schedule will be postponed until the nesting level
* returns to zero.
*
* The caller is responsible for disabling interrupts.
*
* Returns : None defined.
*
**************************************************************/
void
Sched::schedule(void)
{
Task * pOldTask;
Task * pNewTask;
if(state != Started) return;
//
// Postpone rescheduling until all interrupts are completed.
//
if(interruptLevel != 0)
{
bSchedule = 1;
return;
}
//
// If there is a higher-priority ready task, switch to it.
//
if(pRunningTask != readyList.pTop)
{
pOldTask = pRunningTask;
pNewTask = readyList.pTop;
pNewTask->state = Running;
pRunningTask = pNewTask;
if(pOldTask == NULL)
{
contextSwitch(NULL, &pNewTask->context);
}
else
{
pOldTask->state = Ready;
contextSwitch(&pOldTask->context, &pNewTask->context);
}
}
} /* schedule() */
正如你從代碼中看到的一樣,有兩種情況調度程序不啟動設備場景的切換。第一種情況是如果多任務沒有被啟用的時候。這是必要的,因為有時應用程序員想要在調度程序真正啟動之前創建其任務的一些或者全部。在那種情況下,應用程序的main 例程會類似于下面這段
tb程序。每次一個Task 對象被創建的時候,調度程序就被調用(注1)。然而,因為調度程序為了檢查多任務是否已被啟動而檢測變量state 的值,所以直到start()被調用以后才會發生設備場景的轉換。
#include "adeos.h"
void taskAfunction(void);
void taskBfunction(void);
/*
* Create two tasks, each with its own unique function and priority.
*/
Task taskA(taskAfunction, 150, 256);
Task taskB(taskBfunction, 200, 256);
/**************************************************************
*
* Method : main()
——————————————————————————————————
注 1:記住,任務的創建是我們調度點其中的一個。如果調度程序已經啟動了,新任務仍然可能是最高優先級的就緒任務。
* Description : This is what an application program might look like
* if ADEOS were used as the operating system. This
* function is responsible for starting the operating system only.
*
* Notes : Any code placed after the call to os.start() will never
* be executed. This is because main() is not a task,
* so it does not get a chance to run once the scheduler is started.
*
**************************************************************/
void
main(void)
{
os.start();
// This point will never be reached.
} /* main() */
因為這是一段重要的代碼,所以讓我重新講解你正在看的東西。這是一個你可能作為ADEOS 用戶寫出的應用代碼的例子。你在開始加入頭文件adeos.h 和聲明你的任務。在你聲明了你的任務和調用os.start 之后,
tbw任務函數taskAfunction 和taskBfunction 開始執行(以偽并行的方式)。當然,taskB 在這兩個任務中具有最高的優先級(200),因此它將先運行。然而,只要它由于任何原因放棄對處理器的控制,其他的任務就有機會運行。另一種 ADEOS 調度程序不進行設備場景切換的情況是在中斷進行期間。操作系統跟蹤目前運行的中斷服務例程的嵌套級別,井且只有在嵌套級是零的時候才允許設備場景切換。如果調度程序是從一個ISR 調用的(就像它在時鐘節拍期間一樣),bSchedule 標志被置位,表明只要最外層的中斷處理程序退出,調度程序就應該再次被調用。這個被延遲的調度加快了整個系統中斷響應的時間。