用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




以下是一个参考模型,用于模拟 Round Robin 调度逻辑: ```python class Process: def __init__(self, pid, burst_time): self.pid = pid self.burst_time = burst_time self.remaining_time = burst_time class RoundRobinScheduler: def __init__(self, time_slice): self.time_slice = time_slice self.processes = [] self.current_process_index = 0 def add_process(self, pid, burst_time): self.processes.append(Process(pid, burst_time)) def run(self): while self.get_total_burst_time() > 0: current_process = self.processes[self.current_process_index] if current_process.remaining_time > 0: current_process.remaining_time -= self.time_slice if current_process.remaining_time < 0: current_process.remaining_time = 0 self.current_process_index = (self.current_process_index + 1) % len(self.processes) def get_total_burst_time(self): return sum([process.burst_time for process in self.processes]) def get_average_turnaround_time(self): return sum([process.burst_time - process.remaining_time for process in self.processes]) / len(self.processes) ``` 此模型包括两个类:`Process` 和 `RoundRobinScheduler`。`Process` 类表示一个进程,包含进程 ID 和处理时间等属性。`RoundRobinScheduler` 类表示一个 Round Robin 调度器,包含时间片和进程列表等属性。它还包括 `add_process` 方法,用于添加进程,以及 `run` 方法,用于运行调度算法。在 `run` 方法,我们遍历进程列表并使用 Round Robin 调度算法运行每个进程。最后,我们还提供 `get_total_burst_time` 和 `get_average_turnaround_time` 方法,分别用于计算所有进程的总处理时间和平均周转时间。 这个模型仅供参考,具体实现可能因为不同的需求而有所变化。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值