用c语言写优先数调度算法
时间: 2023-08-16 22:03:24 浏览: 105
优先数调度算法是一种基于进程优先级的调度算法,具体实现如下:
1. 定义进程控制块(PCB)结构体,包含进程id、进程优先级、进程状态等信息。
```c
struct PCB {
int pid;
int priority;
int state; // 进程状态:0-就绪,1-运行,2-阻塞
};
```
2. 定义就绪队列和阻塞队列,以链表形式存储PCB,并实现相关操作函数。
```c
struct PCB ready_queue, block_queue;
void init_queue(struct PCB *queue) {
queue->head = NULL;
queue->tail = NULL;
}
void enqueue(struct PCB *queue, struct PCB *pcb) {
if (queue->head == NULL) {
queue->head = pcb;
queue->tail = pcb;
pcb->next = NULL;
} else {
pcb->next = NULL;
queue->tail->next = pcb;
queue->tail = pcb;
}
}
struct PCB *dequeue(struct PCB *queue) {
if (queue->head == NULL) {
return NULL;
} else {
struct PCB *pcb = queue->head;
queue->head = pcb->next;
if (queue->head == NULL) {
queue->tail = NULL;
}
return pcb;
}
}
void remove_pcb(struct PCB *queue, struct PCB *pcb) {
if (queue->head == NULL) {
return;
}
if (queue->head == pcb) {
queue->head = pcb->next;
if (queue->tail == pcb) {
queue->tail = NULL;
}
return;
}
struct PCB *p = queue->head;
while (p->next != NULL && p->next != pcb) {
p = p->next;
}
if (p->next == pcb) {
p->next = pcb->next;
if (queue->tail == pcb) {
queue->tail = p;
}
return;
}
}
```
3. 实现优先数调度算法的主函数,根据优先级将PCB插入到就绪队列中,并选择优先级最高的进程运行。
```c
void priority_scheduling() {
int time = 0;
struct PCB *running_proc = NULL;
while (ready_queue.head != NULL || block_queue.head != NULL || running_proc != NULL) {
// 将到达时间为time的进程加入就绪队列
while (proc_list != NULL && proc_list->arrival_time == time) {
struct PCB *pcb = proc_list;
proc_list = proc_list->next;
pcb->next = NULL;
enqueue(&ready_queue, pcb);
}
// 如果当前没有正在运行的进程,则从就绪队列中选择优先级最高的进程运行
if (running_proc == NULL) {
running_proc = dequeue(&ready_queue);
if (running_proc != NULL) {
running_proc->state = 1;
}
}
// 运行当前进程
if (running_proc != NULL) {
printf("time: %d, running process: %d\n", time, running_proc->pid);
running_proc->priority--;
running_proc->burst_time--;
// 如果当前进程已经完成,则将其从运行队列中移除
if (running_proc->burst_time == 0) {
running_proc->state = 3;
running_proc = NULL;
}
// 如果当前进程被阻塞,则将其从运行队列中移除,并加入阻塞队列
else if (rand() % 100 < block_prob) {
running_proc->state = 2;
remove_pcb(&ready_queue, running_proc);
enqueue(&block_queue, running_proc);
running_proc = NULL;
}
}
// 将到达时间为time的阻塞进程加入就绪队列
while (block_queue.head != NULL && block_queue.head->arrival_time == time) {
struct PCB *pcb = dequeue(&block_queue);
pcb->state = 0;
enqueue(&ready_queue, pcb);
}
time++;
}
}
```
需要注意的是,以上代码仅为示例,实际应用时需要根据具体需求进行修改和完善。
阅读全文