所以我正在编写一个时间片为1的简单Round Robin Scheduler。
这是输入(第一个数字是到达时间,第二个是突发时间)
0 3
2 6
4 4
6 5
8 2
这是预期的输出(cpu是正在执行的内容,就绪队列正在等待。字母表中的字母用于指示正在运行的进程以及剩余时间之后的数字):< / p>
time cpu ready queue (pid/rst)
---- --- ---------------------
0 A3 --
1 A2 --
2 B6 A1
3 A1 B5
4 B5 C4
5 C4 B4
6 B4 D5, C3
7 D5 C3, B3
8 C3 B3, E2, D4
9 B3 E2, D4, C2
10 E2 D4, C2, B2
11 D4 C2, B2, E1
12 C2 B2, E1, D3
13 B2 E1, D3, C1
14 E1 D3, C1, B1
15 D3 C1, B1
16 C1 B1, D2
17 B1 D2
18 D2 --
19 D1 --
但是我的就绪队列出错了。应该在抢占之前将到达物添加到就绪队列的后部(请参阅如何将D5添加到C3之前的就绪队列中)
这就是我得到的:
time cpu ready_queue (pid/rst)
---- --- ---------------------
0 A3 --
1 A2 --
2 B6 --
3 A1 --
4 B5 --
5 C4 --
6 D5 --
7 B4 --
8 C3 --
9 D4 --
10 E2 --
11 B3 --
12 C2 --
13 D3 --
14 E1 --
15 B2 --
16 C1 --
17 D2 --
18 B1 --
19 D1 --
这是我的代码:
#include <stdio.h>
#include <stdlib.h>
#define TS 1
struct process
{
char pid;
int arrival_time;
int service_time;
int remaining_time;
int departure_time;
int turnaround_time;
int wait_time;
};
struct process processes[26];
char pid_rst[2];
char alphabet[26] = {'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'};
int num_processes = 0;
int total_time;
char* create_id(char c, int i)
{
sprintf(pid_rst, "%c%d", c, i);
return pid_rst;
}
void get_processes()
{
int a_t;
int s_t;
int i = 0;
while((scanf("%d %d", &a_t, &s_t) == 2))
{
processes[i].pid = alphabet[i];
processes[i].arrival_time = a_t;
processes[i].service_time = s_t;
processes[i].remaining_time = processes[i].service_time;
i++;
num_processes++;
total_time += processes[i].service_time;
}
}
int main()
{
int time;
int count;
int remain;
int flag = 0;
int i;
int w;
get_processes();
char* cpu_queue[1];
char* wait_queue[num_processes];
remain = num_processes;
for(i = 0; i < num_processes; i++)
{
wait_queue[i] = "--";
}
printf("\ntime\tcpu\tready_queue (pid/rst)\n");
printf("----\t---\t---------------------\n");
for(time = 0, i = 0; remain != 0;)
{
w = 1;
if(processes[i].remaining_time <= TS && processes[i].remaining_time > 0)
{
printf(" %d\t%s\t%s\n", time, create_id(processes[i].pid, processes[i].remaining_time), wait_queue[w-1]);
time += processes[i].remaining_time;
processes[i].remaining_time = 0;
flag = 1;
}
else if (processes[i].remaining_time > 0)
{
printf(" %d\t%s\t%s\n", time, create_id(processes[i].pid, processes[i].remaining_time), wait_queue[w-1]);
processes[i].remaining_time -= TS;
time += TS;
}
if(processes[i].remaining_time == 0 && flag == 1)
{
remain--;
processes[i].turnaround_time += time - processes[i].arrival_time;
processes[i].wait_time += time - processes[i].arrival_time - processes[i].service_time;
processes[i].departure_time = time;
flag = 0;
}
if(i == num_processes-1)
{
i = 0;
}
else if(processes[i+1].arrival_time <= time)
{
wait_queue[w] = create_id(processes[i].pid, processes[i].remaining_time);
if(w < 4)
w++;
i++;
}
else
{
i = 0;
}
}
return 0;
}