时间片轮转调度算法c#
时间: 2023-07-27 11:14:00 浏览: 97
时间片轮转调度算法是一种常见的进程调度算法,其基本思想是将CPU的使用时间划分为若干个时间片,每个进程在一个时间片内运行完毕后,就将CPU让给下一个进程,以此类推。以下是C#实现时间片轮转调度算法的示例代码:
```csharp
using System;
using System.Collections.Generic;
namespace TimeSliceScheduling
{
class Program
{
static void Main(string[] args)
{
int quantum = 2; // 时间片长度
List<Process> processes = new List<Process>
{
new Process("P1", 0, 5),
new Process("P2", 1, 3),
new Process("P3", 2, 4),
new Process("P4", 3, 2),
new Process("P5", 4, 4)
};
TimeSliceScheduling(processes, quantum);
}
static void TimeSliceScheduling(List<Process> processes, int quantum)
{
Queue<Process> queue = new Queue<Process>(processes);
int currentTime = 0;
while (queue.Count > 0)
{
Process process = queue.Dequeue();
Console.WriteLine($"Process {process.Name} is running...");
int timeUsed = Math.Min(quantum, process.BurstTime);
process.BurstTime -= timeUsed;
currentTime += timeUsed;
// 如果进程还未完成,将其重新放入队列尾部
if (process.BurstTime > 0)
{
queue.Enqueue(process);
}
else
{
Console.WriteLine($"Process {process.Name} has finished at time {currentTime}");
}
}
}
}
class Process
{
public string Name { get; }
public int ArrivalTime { get; }
public int BurstTime { get; set; }
public Process(string name, int arrivalTime, int burstTime)
{
Name = name;
ArrivalTime = arrivalTime;
BurstTime = burstTime;
}
}
}
```
在上述示例代码中,我们定义了一个`Process`类来表示进程,其中包括进程名称、到达时间和执行时间等属性。`TimeSliceScheduling`方法接受进程列表和时间片长度作为参数,并使用队列来模拟进程的轮转。在每个时间片内,我们从队列头部取出一个进程并执行,执行完后判断进程是否已完成,如果未完成则将其重新加入队列尾部。当队列为空时,所有进程的执行就完成了。
相关推荐
![text/x-c++](https://img-home.csdnimg.cn/images/20210720083646.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)