操作系統 RR輪轉調度算法(C++實現)


1. 基本原理

  在輪轉(RR)法中,系統根據FCFS策略,將所有的就緒進程排成一個就緒隊列,並可設置每隔一定時間間隔(即時間片)即產生一次中斷,激活系統中的進程調度程序,完成一次調度,將CPU分配給隊首進程,令其執行。

  進程切換時機:

  • 若一個時間片尚未用完,進程就已經結束,則立即激活調度程序,將其從隊列中刪除,並啟動一個新的時間片。
  • 在一個時間片用完時,進程尚未結束,則將其送往隊尾。

2. 代碼實現

  2.1 初始化數據

作業情況

\

時間片

進程名 0  1 2 3 4 平均
到達時間 0 1 2 3 4  
服務時間 4 3 4 2 4  

RR

q = 4

完成時間 4 7 11 13 17  
周轉時間 4 6 9 10 13 8.4
帶權周轉時間 1 2 2.25 5 3.25 2.5

  2.2 RR實現函數

 1 //RR輪轉調度算法
 2 void RoundRobin( vector<int> T, vector<double> S, vector<int> &FT, vector<int> &WT 
 3             , vector<double> &WWT){
 4     int q , CurTime = 0, count = 0;
 5     printf("Please enter the number of piece:\n");
 6     cin >> q;
 7     queue<int> list;
 8     vector<double> _S = S; //用來存儲服務時間
 9     while(CurTime < 17){
10         while( T[count] <= CurTime && count < T.size())
11             list.push(count ++);
12         // 利用隊列完成時間片輪轉
13         if( ! list.empty() ){
14             int temp = list.front();
15             list.pop();
16             for( int i = 0; i < q; i ++, S[temp] --, CurTime ++){
17                 if( S[temp] > 0)
18                     printf("Time %d : Program %d is Running.\n",CurTime ,temp);
19                 else break;
20             }
21             //先判斷是否有新的就緒進程可以入隊
22             while( T[count] <= CurTime && count < T.size())
23                 list.push(count ++);
24             //再將之前未完成的進程入隊
25             if(S[temp] > 0)
26                 list.push(temp);
27             else{
28                 printf("Time %d : Program %d is over.\n", CurTime ,temp);
29                 FT[temp] = CurTime; WT[temp] = FT[temp] - T[temp]; WWT[temp] = WT[temp] / _S[temp];
30             }
31         }
32         else
33             printf( "Time %d : No Program is Running.\n", CurTime ++);
34     }
35 
36 }


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM