优先级调度算法(C++实现)
生活随笔
收集整理的這篇文章主要介紹了
优先级调度算法(C++实现)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
算法思想:
優先級調度算法:
(1)假設系統中有5個進程,每個進程有一個進程控制塊(PCB)來標識。進程控制塊內容包括:進程名,鏈接指針,進程的優先級,估計運行時間,進程狀態。 進程的優先數由用戶自己指定或程序任意設定,且優先數越低,優先級越高,調度時,總是選擇優先級最高的進程運行。
(2)為了調度方便,設計一個指針指向5個進程排成的就緒隊列的第一個進程,另外再設一個當前運行進程指針,指向當前正在運行的進程。
(3)處理機調度時總是選擇隊列中優先級最高的進程運行。為了采用動態優先級調度,進程每運行一次,其優先級就減1。由于本實驗是模擬試驗,所以對被選中進程并不實際啟動運行,而只是執行:優先數加1和估計運行時間減1。用這兩個操作來模擬進程的一次運行。
(4)進程運行一次后,若剩余的運行時間不為0,且其優先級低于就緒隊列的優先級,則選擇一個高優先級進程搶占CPU;若剩余時間為0,則把它的狀態改為完成態(C),并撤出就緒隊列。
(5)若就緒隊列非空,則重復上述的(3)和(4),直到所有進程為完成態。
(6)在所設計的程序中應有顯示或打印語句,能顯示或打印正運行進程的進程名、運行一次后進程的變化、就緒隊列中各進程排隊情況等。
代碼:
#include<iostream> #include<string> #include<queue> using namespace std; typedef struct pcb {string pName;//進程名int priorityNumber;//優先數float serviceTime;//服務時間float estimatedRunningtime;//估計運行時間char state;//狀態bool operator<(const struct pcb &a)const {return priorityNumber > a.priorityNumber || priorityNumber == a.priorityNumber&&estimatedRunningtime > a.estimatedRunningtime;} }PCB;void createProcess(priority_queue<PCB> &p, int n) {//創建n個進程,帶頭結點cout << endl << endl << "創建進程" << endl;PCB r;//工作結點for (int i = 0; i<n; i++) {cout << "請輸入第" << i + 1 << "個進程的名字、優先數、服務時間(例如:A 12 8 ):";cin >> r.pName;cin >> r.priorityNumber;cin >> r.serviceTime;r.estimatedRunningtime = r.serviceTime;r.state = 'R';p.push(r);}cout << endl; }void printProcess(priority_queue<PCB> p) {PCB s;cout << "進程名\t優先數 服務時間 已運行時間 還剩運行時間" << endl;while (p.size() != 0) {s = p.top();cout << s.pName << "\t" << s.priorityNumber << "\t " << s.serviceTime << "\t ";cout << s.serviceTime - s.estimatedRunningtime << "\t " << s.estimatedRunningtime << endl;p.pop();}cout << endl; }void runProcess(priority_queue<PCB> &p) {//運行進程PCB s;while(p.size()!=0){s = p.top();p.pop();cout << "正在運行的進程" << endl;cout << "進程名\t優先數 服務時間 已運行時間 還剩運行時間" << endl;//輸出當前進程cout << s.pName << "\t" << s.priorityNumber << "\t " << s.serviceTime << "\t ";cout << s.serviceTime - s.estimatedRunningtime << "\t " << s.estimatedRunningtime << endl;s.priorityNumber++;//優先數加1s.estimatedRunningtime--;//估計運行時間減1if (s.estimatedRunningtime == 0) {s.state = 'C';}elsep.push(s);cout << "進程" << s.pName << "執行一次之后就緒隊列中的進程" << endl;printProcess(p);}cout << endl; }int main() {priority_queue<PCB> p;int n;cout << "請輸入進程的個數:";cin >> n;createProcess(p, n);runProcess(p);getchar();getchar();return 0; }實驗結果:
總結
以上是生活随笔為你收集整理的优先级调度算法(C++实现)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 先来先服务调度算法(C++实现)
- 下一篇: 按时间片轮转调度算法(C++实现)