单处理机的进程调度-优先级调度策略
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
#include<iostream>
using namespace std;
typedef struct PCB{
/*用PCB来表示一个进程,PCB结构体的创建*/
int id;//进程名
struct PCB*next; //五个进程连成队列,用指针指出下一个进程的进程控制块的首地址,最后一个进程中的指针为“0”。
int runtime; //运行时间:进程需要运行的单位时间数
int priority; //优先数,总是选取优先数大的先执行
char status; //就绪R,结束E
}*pcb;
void create(PCB *h){
/*创建预先队列,将进程按照给定的优先级从大到小构成一个优先队列。
首先创建链表表头,之后依次将优先级最大的进程插入至表头之后。
*/
h->next=NULL;
int a,b;//a为进程要求运行时间,b为进程优先级
for(int i=0;i<5;i++)
{
cout<<"进程P"<<i+1<<" :"<<endl;
cin>>a>>b;
PCB *p=new PCB;
PCB *q=h->next;
//输入进程p的信息
p->id=i+1;
p->runtime=a;
p->priority=b;
p->status='R';
if((q==NULL)||(p->priority>q->priority))
{
/* 如果q进程为空,或者输入进程p优先级大于第一个进程优先级,将其插入头指针之后*/
p->next=h->next;
h->next=p;
continue;
}
while((p->priority<q->next->priority)&&(q->next!=NULL))
{
/*如不是,那么寻找第一个优先级小于输入进程的进程,将输入进程插入其之前*/
q=q->next;
}
p->next=q->next;
q->next=p;
}
}
void sort(PCB *h){
if(h->next->runtime==0)
{
/*如果进程要求运行时间为0则将其状态改为“E”,并从优先队列中删除*/
h->next->status='E';
h->next=h->next->next;
return;
}
PCB *p=h->next;
h->next=p->next;
PCB *q=h->next;
if((q==NULL)||(p->priority>q->priority))
{
p->next=h->next;
h->next=p;
return;
}
while((q->next!=NULL)&&(p->priority<=q->next->priority))
{
q=q->next;
}
p->next=q->next;
q->next=p;
}
void call(PCB *h){
cout<<"进程调用 P"<<h->next->id<<endl;
h->next->runtime--;
h->next->priority--;
}
void show(PCB *h){
PCB *p=h->next;
while(p!=NULL)
{
cout<<" p"<<p->id <<" "<<p->runtime <<" "<<p->priority <<" "<<p->status <<endl;
p=p->next;
}
}
void main(){
cout<<"请输入各个进程的运行时间及其优先级:"<<endl;
PCB *h=new PCB;
create(h);
cout<<"\n\n五个进程的进程队列如下:"<<endl;
show(h);
cout<<"\n\n进程执行过程如下:"<<endl;
while(h->next!=NULL)
{
call(h);
sort(h);
show(h);
}
}。