抢占式优先级调度算法(进程不在同一时刻到达)c语言代码
时间: 2023-07-29 17:11:23 浏览: 109
以下是一个简单的抢占式优先级调度算法的 C 语言代码示例:
```c
#include <stdio.h>
#include <stdlib.h>
#define MAX_PROCESSES 10
struct process {
int pid;
int priority;
int burst_time;
int remaining_time;
};
struct process queue[MAX_PROCESSES];
int front = -1, rear = -1;
void enqueue(struct process p) {
if (rear == MAX_PROCESSES - 1) {
printf("Queue is full.\n");
exit(0);
}
if (front == -1) {
front = 0;
}
rear++;
queue[rear] = p;
}
struct process dequeue() {
if (front == -1 || front > rear) {
printf("Queue is empty.\n");
exit(0);
}
struct process p = queue[front];
front++;
return p;
}
int main() {
int num_processes, i, j, time_slice;
struct process p[MAX_PROCESSES], temp;
printf("Enter the number of processes: ");
scanf("%d", &num_processes);
for (i = 0; i < num_processes; i++) {
printf("Enter details of process %d:\n", i + 1);
printf("PID: ");
scanf("%d", &p[i].pid);
printf("Priority: ");
scanf("%d", &p[i].priority);
printf("Burst Time: ");
scanf("%d", &p[i].burst_time);
p[i].remaining_time = p[i].burst_time;
enqueue(p[i]);
}
printf("Enter the time slice: ");
scanf("%d", &time_slice);
for (i = 0; i < num_processes - 1; i++) {
for (j = i + 1; j < num_processes; j++) {
if (p[i].priority > p[j].priority) {
temp = p[i];
p[i] = p[j];
p[j] = temp;
}
}
}
printf("\nProcess Execution Order: ");
int total_time = 0;
while (front != -1) {
struct process current = dequeue();
if (current.remaining_time <= time_slice) {
total_time += current.remaining_time;
printf("%d ", current.pid);
current.remaining_time = 0;
} else {
current.remaining_time -= time_slice;
total_time += time_slice;
enqueue(current);
}
for (i = 0; i < num_processes; i++) {
if (queue[front].priority < p[i].priority) {
enqueue(dequeue());
break;
}
}
}
printf("\nTotal Time Taken: %d", total_time);
return 0;
}
```
该程序首先读取输入的进程数和每个进程的 PID、优先级和 CPU 执行时间,将它们作为结构体的成员并将每个进程添加到队列中。然后,它按照进程优先级对队列中的进程进行排序。
接下来,程序会读取时间片大小,并开始执行抢占式优先级调度算法。它将从队列中取出具有最高优先级的进程,并根据其剩余执行时间确定要执行的时间片大小。如果进程的剩余执行时间小于等于时间片大小,则进程将被完全执行,并从队列中删除。否则,它将被重新添加到队列中,并将其剩余执行时间减去时间片大小。
在每次迭代中,程序将检查队列中是否有更高优先级的进程。如果有,则会暂停当前进程的执行,并放置在队列的末尾,直到更高优先级的进程完成执行。程序将继续循环,直到队列为空。
最后,程序将输出进程的执行顺序和总执行时间。
阅读全文