⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 progress.cpp

📁 操作系统调度算法按照优先级的大小找到适合新进程的位置进行排序
💻 CPP
字号:
#include <iostream>
using namespace std;
#define ERROR 0
#define OK 1
#define NULL 0
enum process_state{W,R,F}; //进程状态枚举类型(等待,运行,就绪)

typedef struct PCBNode //PCB结构体
{
	char name; //名字
    int priority; //权限
    int arrive; //到达时间
    int demand;//需要运行的时间
    int use;//已用CPU时间
    process_state state; //状态
}PCBNode,*pcb;

InitPcb(pcb &L) //初始化PCB指针
{
	L=(PCBNode*)malloc(sizeof(PCBNode)); //创建结点
    if(!L) 
		return ERROR;
    return OK;
}

typedef struct PNode //PCB链表结点结构体
{
	pcb process;
    struct PNode *next;
}PNode;

typedef struct //带头结点的PCB链表指针
{
	PNode* head;
}pcblist;

InitPcbList(pcblist &L) //初始化PCB链表
{
	L.head=(PNode*)malloc(sizeof(PNode));
    if (L.head)
		L.head->next=NULL;
    else
		return ERROR;
	return OK;
}

int pcblistinsert(pcblist &L,pcb e) //PCB链表中插入新的结点
{
	PNode *p,*s;
    p=L.head;
    while (p->next && e->priority < p->next->process->priority)
	{ //按照优先级的大小找到适合新进程的位置
		p=p->next;
	}
	s=(PNode*)malloc(sizeof(PCBNode));
	s->process=e;
	s->next=p->next;
	p->next=s;
	return OK;
}

void main()
{
	pcblist L;
	InitPcbList(L);   //初始链表
	pcb x;
	x=(pcb)malloc(sizeof(PCBNode)); //生成新结点
	char c,d;
	int i=1,j;
	PNode* h;
	pcb P[5];
	for (j=0;j<5;j++)
		InitPcb(P[j]);
	for (j=0;j<5;j++)
	{
		cout<<"进程名:";cin>>P[j]->name;
		cout<<"优先级:";cin>>P[j]->priority;
		cout<<"到达时间:";cin>>P[j]->arrive;
		cout<<"需要运行时间:";cin>>P[j]->demand;
		P[j]->use=0;
		P[j]->state=W;
		cout<<endl; 
	}
	//只要有进程未完成
	while (P[0]->state!=F||P[1]->state!=F||P[2]->state!=F||P[3]->state!=F||P[4]->state!=F)
	{
		h=L.head;
		c='a';
		for (j=0;j<5;j++)
			if (P[j]->arrive==i)
				pcblistinsert(L,P[j]);
			if(h->next==NULL)
			{
				i++;
				continue;
			}
			x=h->next->process;
			x->state=R;
			//输出进程状况
			cout<<"_____________________________________________________\n\n";
			cout<<"进程名 优先级 到达时间 需要运行时间 已用CPU时间 状态 "<<endl;
			for (j=0;j<5;j++)
			{
				switch (P[j]->state)
				{
				case W:d='W';break;
				case R:d='R';break;
				case F:d='F';break;
				}
				cout<<"  "<<P[j]->name<<"\t  ";
                cout<<P[j]->priority<<"\t  ";
                cout<<P[j]->arrive<<"\t    ";
                cout<<P[j]->demand<<"\t\t ";
                cout<<P[j]->use<<"\t  "<<d<<endl;
			}
			x->priority--;
			x->use++;
			if(x->use==x->demand)//如果已用时间等于需要的时间,则进程就完成了
				x->state=F;
			else x->state=W;  //否则就进入等待对列
			L.head=L.head->next;
			if(x->state!=F)
			{
				pcblistinsert(L,x);
			}
			i++; //时间片加1
			cout<<"按任意键继续"<<endl;
			c=getchar(); //控制时间片间隔显示
	}
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -