实验:进程调度

99 阅读2分钟

实验:进程调度

1. 实验内容

设计一个时间片轮转调度算法实现处理机调度的程序,具体内容如下:

(1)实验中使用的数据结构

PCB 进程控制块:

  • 进程名 name
  • 要求运行时间 runtime
  • 优先数 prior
  • 状态 state
  • 已运行时间 runedtime

为简单起见,只设运行队列就绪链表两种数据结构,进程的调度在这两个队列中切换

image.png

(2)每个进程运行时间随机产生,为 1~20 之间的整数

(3)时间片的大小由实验者自己定义,可为 3 或 5

(4)可参考的程序流程图

image.png

2. 程序

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

struct PCB{
    int name;
    int runtime;
    int prior;
    int state;
    int runedtime;
    struct PCB* next;
};

int main() {
    srand((unsigned) time(NULL));   // 以时间为种子

    int time_slot = 3;   // 设置时间片大小为3

    struct PCB *running_queue = (struct PCB*) malloc(sizeof (struct PCB));  // 运行队列
    struct PCB *waiting_queue = (struct PCB*) malloc(sizeof (struct PCB));  // 就绪队列

    // 建立就绪队列,初始化10个进程
    int i;
    struct PCB *tail = waiting_queue;   // 就绪队列的队尾
    for(i=0;i<10;i++){
        struct PCB *p = (struct PCB*) malloc(sizeof (struct PCB));
        p->name = i+1;
        p->runtime = rand()%20+1;    // 随机产生的运行时间,1-20之间的整数
        p->prior = 1;    // 因为是时间片轮转算法,所以全部默认1即可
        p->state = 0;
        p->runedtime = 0;    // 目前还处于就绪队列,已运行时间为0
        tail->next = p;
        tail = tail->next;
    }

    while(waiting_queue->next != NULL){
        // 取出队头
        struct PCB *p = waiting_queue->next;
        // 插入运行队列
        running_queue->next = p;
        // 从就绪队列中删除p
        waiting_queue->next = p->next;
        p->next = NULL;

        int runtime = p->runtime;
        // 如果运行时间比时间片小的话
        if(runtime < time_slot){
            p->runedtime += p->runtime;
            printf("process name=%d, run=0, runed=%d, killtime=%d\n",p->name, p->runedtime, p->runtime);
            p->runtime = 0;
        }else{
            p->runtime -= time_slot;
            p->runedtime += time_slot;
            printf("process name=%d, run=%d, runed=%d, killtime=%d\n",p->name, p->runtime, p->runedtime, time_slot);
        }

        // 如果没有运行结束,则插回就绪队列队尾
        if(p->runtime != 0){
            tail->next = p;
            tail = tail->next;
        }

        running_queue->next = NULL;
    }

    return 0;
}

3. 程序截图

1.png

2.png

3.png

4. 运行结果

4.png

5.png

5. 修改时间片大小为5

6.png