Round-robin 算法

Round-robin 是一種使用在 進程 和 網絡分配 計算中的算法。 

以 進程分配爲例:


假設我們的time slot ( 單次運行進程的最長時間) 是100 ms,  如果 job1 一共需要消耗250 ms來運行, 那麼 round-robin 分配器就會暫停 job1 在其運行100 ms之後, 然後分配給其他的進程, 並且將 job1 剩下的內容放到隊列中排隊,直到 job1 運行結束。


Process name Arrival time Execute time
P0 0 250
P1 50 170
P2 130 75
P3 190 100
P4 210 130
P5 350 50
以上的圖中表示 進程 0 - 5 的到達時間和運行完成的總時間。


運行隊列如下。


時間 隊列 解釋
0 P0 時間0的時候, P0 到達
100 P1 P0 當運行100ms的時候,應該分配給下一個進程,P1在0~100內到達,P0剩下150 ms需要執行
200 P0 P2 P3 P1 當運行200ms的時候,新進程 P2 和 P3 在100~200內 到達,P1 剩下70ms,
300 P2 P3 P1 P4 P0 當運行300ms的時候,新進程P4 在200~300 內到達,P0 剩下 50ms
375 P3 P1 P4 P0 P5 當從300ms到375ms的時候,進程P2完成,那麼我們將結束它,進而按照隊列繼續工作,注意把在300 ~ 375內到達的P5放進進程隊列中
475 P1 P4 P0 P5 P3結束, 迴歸下隊列中的進程。P1 70ms, P4 130ms  P0 50ms P5 50ms 
545 P4 P0 P5 P1結束
645 P0 P5 P4 P4剩下30ms
695 P5 P4 P0結束
745 P4 P5結束
775   P4結束
   


public static void RoundRobin_Algo(int[] arrTime, int[] exeTime, int timeSlot) {
		if (arrTime == null || exeTime == null || arrTime.length != exeTime.length) {
			System.out.println("Error!");
		}
		
		Queue<process> queue = new LinkedList<process>();
		int index = 0;	
		int totalWaitTime = 0;		//所有進程的等待總時間
		int currentTime = 0;		//當前時間
		int visitedTimes = 0;		//CPU訪問次數
		
		while (!queue.isEmpty() || index < arrTime.length) {
			if (!queue.isEmpty()) {
				visitedTimes ++;
				process tempP = queue.poll();
				//waiting time in total
				totalWaitTime += currentTime - tempP.arrTime;
				//update the currentTime
				currentTime += Math.min(tempP.exeTime, timeSlot);
				
				//add the process which arrived before the end of this process finished.
				for (; index < arrTime.length && arrTime[index] < currentTime; index++) {
					queue.add(new process(arrTime[index], exeTime[index]));
				}
				
				//add the rest of current process into process queue
				if (tempP.exeTime > timeSlot) {
					queue.add(new process(currentTime, tempP.exeTime - timeSlot));
				}
				
			} else {
				queue.add(new process(arrTime[index], exeTime[index]));
				currentTime = arrTime[index];
				index++;
				visitedTimes ++;
			}
		}
		System.out.println("Total wait time among the process: " + totalWaitTime);
		System.out.println("Total CPU visited times: " + visitedTimes);
	}


Let me know, If you found any issues.

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章