1. 程式人生 > >用Python模擬作業系統中的round robin演算法

用Python模擬作業系統中的round robin演算法

#字典儲存單個程序,列表儲存程序表象
processes = [{"arriveTime":0,"serviceTime":3,"name":"A","waitTime":0},{"arriveTime":2,"serviceTime":6,"name":"B","waitTime":0},{"arriveTime":4,"serviceTime":4,"name":"C","waitTime":0},{"arriveTime":6,"serviceTime":5,"name":"D","waitTime":0},{"arriveTime":8,"serviceTime":2,"name":"E","waitTime":0}]
#tmp用於儲存等待和進行排程的程序
tmp = []
maxWaitTime = -1
time = 0
while True:
  for pro in processes:
    if pro["arriveTime"] == time:      
      tmp.append(pro)
      processes.pop(processes.index(pro))
      break
  #全部程序執行完成
  if(len(tmp) == 0 and len(processes) == 0):
    break;
  #找出等待時間最長的程序
  for pro in tmp:
    if pro["waitTime"]>maxWaitTime:
      maxWaitTime = pro["waitTime"]
      num = tmp.index(pro)
    elif pro["waitTime"] == maxWaitTime:
      if(pro["arriveTime"]>tmp[num]["arriveTime"]):
        num = tmp.index(pro)
  tmp[num]["serviceTime"]-=1
  #呼叫過的程序等待時間設為-1,然後全加一次後變為0
  tmp[num]["waitTime"]=-1
  #等待時間整體+1
  for pro in tmp:
      pro["waitTime"]+=1
  if tmp[num]["serviceTime"] == 0:
    print("程序%s執行完成,排程時間為%d" %(tmp[num]["name"],time))
    tmp.pop(num)
    
  else:
    print("程序%s執行排程,排程時間%d"%(tmp[num]["name"],time))
  maxWaitTime = -1

  time += 1