模拟进程调度

功能

data.h

#ifndef _Data_h_
#define _Data_h_

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

#define ElemType PCB
#define Status int
#define OK		1
#define	ERROR	0
#define TimeSlice	1
#define Infinity 10 //INT_MAX


#define NAME_MAXSIZE 20
typedef enum 
{
    Ready,Running,Block
}ProState;

typedef enum 
{
    FCFS, SPF		//先来先服务,短进程优先
}PriorityRule;

typedef struct 
{
    char Name[NAME_MAXSIZE];	//进程名
    int Priority;				//优先数
    int ArrivalTime;			//到达时间		以时间片为单位
    int NeedRunningTime;		//运行时间		以时间片为单位
    int StartTime;				//开始执行时间
    int FinishTime;				//完成时间
    int TimeUsedCPU;			//已用CPU时间		以时间片为单位
    ProState ProcessState;		//进程状态
}PCB;

typedef struct Node
{
    ElemType data;
    struct Node * Next;		
}LNode,*LinkList;



#endif

 ChainList.h

#ifndef _ChainList_h_
#define _ChainList_h_

#include "Data.h"

//功能:链表初始化
Status Init(LinkList *L);

//功能:赋值运算,将e2赋值给e1
void Assignment(ElemType *e1, ElemType e2);

//功能:获取第i个结点元素
Status GetElemt_L(LinkList L,int i,ElemType *e);

//功能:链表根据优先级插入元素
Status ListInsert_L(LinkList L,ElemType e);

//功能:链表删除头结点
Status ListDelete_L(LinkList L,ElemType *e);


#endif

ProPCB.h

#ifndef _ProPCB_h_
#define _ProPCB_h_

#include "ChainList.h"

//功能:将e插入链表Q
Status GetProcess(LinkList Q,ElemType e);		//上就绪队列

//功能:根据不同的优先级规则,返回优先数
int GetPriority(ElemType *e, PriorityRule PR);  //根据不同的规则PR 设置优先数

//功能:将链表Q的头结点数据放到e指向的内存,并删除
Status OutProsess(LinkList Q,ElemType *e);	    //下就绪队列

//功能:CPU运行pcb指向的进程,并输出所有进行进程状态
Status CPURunPro(LinkList Q, PCB *pcb);	        //CPU运行PCB

//功能:打印所有PCB信息
void PrintProQueue(LinkList Q, PCB *pcb);		//打印运行后PCB信息

//功能:当一个进程结束,打印进程信息
void PrintProResult(PCB *pcb);

#endif

实现

#include "ChainList.h"

extern int CPUUsedTime;

//功能:链表初始化
Status Init(LinkList *L)
{
    *L = (LinkList)malloc(sizeof(LNode));
    (*L)->data.NeedRunningTime = -1;
    (*L)->Next = NULL;
    return OK;
}

//功能:赋值运算,将e2赋值给e1
void Assignment(ElemType *e1, ElemType e2)
{
    e1->ArrivalTime = e2.ArrivalTime;
    strcpy(e1->Name,e2.Name);
    e1->Priority = e2.Priority;
    e1->ProcessState = e2.ProcessState;
    e1->FinishTime = e2.FinishTime;
    e1->StartTime = e2.StartTime;
    e1->NeedRunningTime = e2.NeedRunningTime;
    e1->TimeUsedCPU = e2.TimeUsedCPU;
}



//链表中按照优先级:从大到小排序插入
Status ListInsert_L(LinkList L,ElemType e)	//这样修改应该不对 p = *L出错
{
    LinkList p = L->Next, pre = L, s;
    while (p && e.Priority <= p->data.Priority)	
    {
        pre = p;
        p = p->Next;
    }
    s = (LinkList)malloc(sizeof(LNode));
    Assignment(&s->data, e);
    s->Next = pre->Next;
    pre->Next = s;
    return OK;
}
//链表中头部删除
Status ListDelete_L(LinkList L,ElemType *e)
{
    LinkList p = L, q;
    q = p->Next;
    if(!q)
        return ERROR;
    p->Next = q->Next;
    Assignment(e, q->data);
    free(q);
    return OK;
}


#include "ProPCB.h"

extern int CPUUsedTime;

//功能:将e插入链表Q
Status GetProcess(LinkList Q,ElemType e)
{
    return ListInsert_L(Q, e);
}

//功能:根据不同的优先级规则,返回优先数
int GetPriority(ElemType *e, PriorityRule PR)
{
    if(PR == FCFS)
        return Infinity - e->ArrivalTime;
    else if(PR == SPF)
        return Infinity - e->NeedRunningTime;
    else
        printf("GetPriority Function ERROR!\n");
    return ERROR;
}

//功能:将链表Q的头结点数据放到e指向的内存,并删除
Status OutProsess(LinkList Q,ElemType *e)
{
    return ListDelete_L(Q ,e);
}

//上一次CPU运行时间增加1个时间片
Status CPURunPro(LinkList Q,PCB *pcb)
{
    if(pcb->StartTime == -1)
        pcb->StartTime = CPUUsedTime;
    pcb->ProcessState = Running;
    //PrintProQueue(Q, pcb);
    pcb->TimeUsedCPU += TimeSlice;

    return OK;
}

//功能:打印所有PCB信息
void PrintProQueue(LinkList Q, PCB *pcb)
{
    LinkList p = Q->Next;
   
    printf("进程名  优先数  到达时间  运行时间  已用CPU时间  完成时间  进程状态\n");
    if(pcb)
        printf(" %4s     %2d      %4d      %4d     %3d(+1)       %3d        %4s  \n",
        pcb->Name,pcb->Priority,pcb->ArrivalTime,pcb->NeedRunningTime,
        pcb->TimeUsedCPU, pcb->FinishTime,pcb->ProcessState == Ready ? "就绪" : "运行");
    while (p)
    {
        printf(" %4s     %2d      %4d      %4d     %3d           %3d        %4s  \n",
            p->data.Name,p->data.Priority,p->data.ArrivalTime,p->data.NeedRunningTime,
            p->data.TimeUsedCPU,p->data.FinishTime, p->data.ProcessState == Ready ? "就绪" : "运行");
        p = p->Next;
    }
    printf("-------------------------------------------------------------------------------\n");
}

//功能:当一个进程结束,打印进程信息
void PrintProResult(PCB *pcb)
{
    printf("进程名  到达时刻 运行时间 开始时刻 完成时刻 周转时间 带权周转时间 进程状态\n");
    if(pcb)
        printf(" %2s     %3d      %4d        %4d      %3d     %4d       %5.2lf       %4s  \n",
        pcb->Name,pcb->ArrivalTime,pcb->NeedRunningTime,pcb->StartTime,pcb->FinishTime,
        pcb->FinishTime-pcb->ArrivalTime,((pcb->FinishTime - pcb->ArrivalTime)*1.0)/pcb->NeedRunningTime,"完成");

    printf("-------------------------------------------------------------------------------\n");
}


main:

#include "ProPCB.h"

/****************************
*  实验01: 非抢占式静态优先权	*
*  ① 优先权始终保持不变		*
*  ② 一旦进入CPU便运行到结束	*
*  ③ FCFS只考虑到达时间进CPU	*
*  ④ SPF认为到达时间相同		*
****************************/

int CPUUsedTime = 0;

void InputData(LinkList * pPCBdata, PriorityRule PR)
{
    ElemType e = {{0},-1,-1,-1,-1,-1,0,Ready};
    e.ArrivalTime = 0;
    e.ProcessState = Ready;
    e.TimeUsedCPU = 0;
    strcpy(e.Name,"A");
    e.NeedRunningTime = 1;
    e.Priority = GetPriority(&e, PR);
    if(PR == SPF)   e.ArrivalTime = 0;
    GetProcess(*pPCBdata,e);

    e.ArrivalTime = 1;
    e.ProcessState = Ready;
    e.TimeUsedCPU = 0;
    strcpy(e.Name,"B");
    e.NeedRunningTime = 100;
    e.Priority = GetPriority(&e, PR);
    if(PR == SPF)   e.ArrivalTime = 0;
    GetProcess(*pPCBdata,e);

    e.ArrivalTime = 2;
    e.ProcessState = Ready;
    e.TimeUsedCPU = 0;
    strcpy(e.Name,"C");
    e.NeedRunningTime = 1;
    e.Priority = GetPriority(&e, PR);
    if(PR == SPF)   e.ArrivalTime = 0;
    GetProcess(*pPCBdata,e);

    e.ArrivalTime = 3;
    e.ProcessState = Ready;
    e.TimeUsedCPU = 0;
    strcpy(e.Name,"D");
    e.NeedRunningTime = 100;
    e.Priority = GetPriority(&e, PR);
    if(PR == SPF)   e.ArrivalTime = 0;
    GetProcess(*pPCBdata,e);

}

//void InputData1(LinkList * pPCBdata, PriorityRule PR)
//{
//    ElemType e = {{0},-1,-1,-1,-1,-1,0,Ready};
//    e.ArrivalTime = 0;
//    e.ProcessState = Ready;
//    e.TimeUsedCPU = 0;
//    strcpy(e.Name,"A");
//    e.NeedRunningTime = 4;
//    e.Priority = GetPriority(&e, PR);
//    if(PR == SPF)   e.ArrivalTime = 0;
//    GetProcess(*pPCBdata,e);
//
//    e.ArrivalTime = 1;
//    e.ProcessState = Ready;
//    e.TimeUsedCPU = 0;
//    strcpy(e.Name,"B");
//    e.NeedRunningTime = 3;
//    e.Priority = GetPriority(&e, PR);
//    if(PR == SPF)   e.ArrivalTime = 0;
//    GetProcess(*pPCBdata,e);
//
//    e.ArrivalTime = 2;
//    e.ProcessState = Ready;
//    e.TimeUsedCPU = 0;
//    strcpy(e.Name,"C");
//    e.NeedRunningTime = 5;
//    e.Priority = GetPriority(&e, PR);
//    if(PR == SPF)   e.ArrivalTime = 0;
//    GetProcess(*pPCBdata,e);
//
//    e.ArrivalTime = 3;
//    e.ProcessState = Ready;
//    e.TimeUsedCPU = 0;
//    strcpy(e.Name,"D");
//    e.NeedRunningTime = 2;
//    e.Priority = GetPriority(&e, PR);
//    if(PR == SPF)   e.ArrivalTime = 0;
//    GetProcess(*pPCBdata,e);
//
//    e.ArrivalTime = 4;
//    e.ProcessState = Ready;
//    e.TimeUsedCPU = 0;
//    strcpy(e.Name,"E");
//    e.NeedRunningTime = 4;
//    e.Priority = GetPriority(&e, PR);
//    if(PR == SPF)   e.ArrivalTime = 0;
//    GetProcess(*pPCBdata,e);
//}


int main(void)
{
    LinkList PCBQueue;	//InitPCBdata里面存放PCB初始数据
    ElemType e = {{0},-1,-1,-1,-1,-1,0,Ready};
    ElemType *pcb = NULL;
    PriorityRule PR;
    PR = FCFS;	   //   SPF    or   FCFS
    //***********    初始化就绪队列    *************//
    Init(&PCBQueue);
    InputData(&PCBQueue, PR);
    printf("初始数据如下:\n");
    PrintProQueue(PCBQueue, pcb);

    //***********    进程根据优先级上CPU    *************//
    printf("\n进程运行信息如下:\n");
    while (OutProsess(PCBQueue, &e))
    {
        //一次性运行完毕
        while(e.TimeUsedCPU < e.NeedRunningTime)	//上完CPU的进程是否完毕
        {
            CPURunPro(PCBQueue, &e);		        //上CPU
            ++CPUUsedTime;					        //CPU时间增加
        }
    //***********    当进程执行完毕时打印输出    *************//
        e.FinishTime = CPUUsedTime;
        PrintProResult(&e);
    }

	getchar();
    return 0;
}

 

  • 18
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
  本模拟程序实现对n个进程根据优先权的高低调度的模拟,创建进程描述符PCB,进程的优先权在运行过程中动态改变,每个时间片结束后显示当前各进程的状态。具体要求如下: 用C语言来实现对n个进程采用不同调度算法的进程调度。 每个用来标识进程进程控制块PCB用结构来描述,包括以下字段:  进程标识数 ID。 进程优先数 PRIORITY,并规定优先数越大的进程,其优先权越高。 进程已占用的CPU时间CPUTIME。 进程还需占用的CPU时间NEEDTIME。当进程运行完毕时,NEEDTIME变为0。 进程的阻塞时间STARTBLOCK,表示当进程再运行STARTBLOCK个时间片后,将进入阻塞状态。 进程被阻塞的时间BLOCKTIME,表示已阻塞的进程再等待BLOCKTIME个时间片后,将转换成就绪状态。 进程状态STATE。 队列指针NEXT,用来将PCB排成队列。 优先数改变的原则: 进程在就绪队列中呆一个时间片,优先数加1。 进程每运行一个时间片,优先数减3。 假设在调度前,系统中有5个进程,它们的初始状态如下: ID 0 1 2 3 4 PRIORITY 9 38 30 29 0 CPUTIME 0 0 0 0 0 ALLTIME 3 3 6 3 4 STARTBLOCK 2 -1 -1 -1 -1 BLOCKTIME 3 0 0 0 0 STATE READY READY READY READY READY 为了清楚的观察各进程调度过程,程序应将每个时间片内的情况显示出来,参照的具体格式如下: RUNNING PROG:i READY-QUEUE:-〉id1-〉id2 BLOCK-QUEUE:-〉id3-〉id4 = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = == = = ID 0 1 2 3 4 PRIORITY P0 P1 P2 P3 P4 CUPTIME C0 C1 C2 C3 C4 ALLTIME A0 A1 A2 A3 A4 STARTBLOCK T0 T1 T2 T3 T4 BLOCKTIME B0 B1 B2 B3 B4 STATE S0 S1 S2 S3 S4
调度是操作系统中非常重要的一部分,其主要功能是为了合理地利用系统资源,提高系统的运行效率。在 Python 中模拟进程调度可以通过模拟进程的状态、优先级和时间片等来实现。 下面是一个简单的模拟进程调度的示例代码: ```python # 定义进程类 class Process: def __init__(self, pid, name, priority, burst_time): self.pid = pid # 进程ID self.name = name # 进程名称 self.priority = priority # 进程优先级 self.burst_time = burst_time # 进程执行时间 self.wait_time = 0 # 进程等待时间 self.turnaround_time = 0 # 进程周转时间 def __repr__(self): return f"Process {self.pid} ({self.name}): priority={self.priority}, burst_time={self.burst_time}" # 定义进程调度器类 class Scheduler: def __init__(self, processes): self.processes = processes # 进程列表 self.time_quantum = 2 # 时间片大小 # 先来先服务调度算法 def fcfs(self): current_time = 0 total_wait_time = 0 total_turnaround_time = 0 for process in self.processes: process.wait_time = current_time process.turnaround_time = process.wait_time + process.burst_time total_wait_time += process.wait_time total_turnaround_time += process.turnaround_time current_time += process.burst_time avg_wait_time = total_wait_time / len(self.processes) avg_turnaround_time = total_turnaround_time / len(self.processes) print("先来先服务调度算法:") print(f"平均等待时间:{avg_wait_time:.2f}") print(f"平均周转时间:{avg_turnaround_time:.2f}") # 时间片轮转调度算法 def round_robin(self): current_time = 0 total_wait_time = 0 total_turnaround_time = 0 queue = self.processes.copy() while queue: process = queue.pop(0) if process.burst_time > self.time_quantum: process.burst_time -= self.time_quantum current_time += self.time_quantum queue.append(process) else: process.wait_time = current_time process.turnaround_time = process.wait_time + process.burst_time total_wait_time += process.wait_time total_turnaround_time += process.turnaround_time current_time += process.burst_time avg_wait_time = total_wait_time / len(self.processes) avg_turnaround_time = total_turnaround_time / len(self.processes) print("时间片轮转调度算法:") print(f"平均等待时间:{avg_wait_time:.2f}") print(f"平均周转时间:{avg_turnaround_time:.2f}") # 测试 processes = [ Process(1, "P1", 2, 5), Process(2, "P2", 1, 3), Process(3, "P3", 3, 8), Process(4, "P4", 4, 6), Process(5, "P5", 5, 4), ] scheduler = Scheduler(processes) scheduler.fcfs() scheduler.round_robin() ``` 该代码定义了进程类和进程调度器类,并实现了先来先服务调度算法和时间片轮转调度算法。测试时创建了 5 个进程,并分别用两种算法进行调度,输出了平均等待时间和平均周转时间。 需要注意的是,该示例代码只是一个简单的模拟,实际的进程调度算法还需要考虑更多的因素,如进程的状态转换、中断、优先级调度等。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

兔老大RabbitMQ

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值