RR调度算法的C语言代码链表
时间: 2024-05-11 16:11:12 浏览: 12
RR调度算法(Round-Robin Scheduling Algorithm)是一种常用的调度算法,它按照时间片轮转的方式为每个进程分配CPU时间。下面是一个使用C语言实现的简单的RR调度算法的代码示例:
```c
#include <stdio.h>
#include <stdlib.h>
// 定义进程结构体
typedef struct Process {
int pid; // 进程ID
int burstTime; // 执行时间
int remainingTime; // 剩余执行时间
} Process;
// 定义链表节点结构体
typedef struct Node {
Process process;
struct Node* next;
} Node;
// 创建新的链表节点
Node* createNode(Process process) {
Node* newNode = (Node*)malloc(sizeof(Node));
newNode->process = process;
newNode->next = NULL;
return newNode;
}
// 在链表尾部插入节点
void insertAtEnd(Node** head, Process process) {
Node* newNode = createNode(process);
if (*head == NULL) {
*head = newNode;
} else {
Node* temp = *head;
while (temp->next != NULL) {
temp = temp->next;
}
temp->next = newNode;
}
}
// 执行RR调度算法
void runRR(Node* head, int timeSlice) {
Node* current = head;
while (current != NULL) {
if (current->process.remainingTime > 0) {
if (current->process.remainingTime > timeSlice) {
printf("Process %d is running for time slice %d\n", current->process.pid, timeSlice);
current->process.remainingTime -= timeSlice;
} else {
printf("Process %d is running for remaining time %d\n", current->process.pid, current->process.remainingTime);
current->process.remainingTime = 0;
}
}
current = current->next;
}
}
int main() {
// 创建进程链表
Node* head = NULL;
insertAtEnd(&head, (Process){1, 10, 10});
insertAtEnd(&head, (Process){2, 5, 5});
insertAtEnd(&head, (Process){3, 8, 8});
// 执行RR调度算法,时间片为2
runRR(head, 2);
return 0;
}
```
上述代码中,首先定义了进程结构体和链表节点结构体。然后,通过`createNode`函数创建新的链表节点,`insertAtEnd`函数将节点插入链表尾部。最后,`runRR`函数执行RR调度算法,遍历链表中的每个进程,并根据时间片的大小进行调度。