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

📄 进程调度模拟.cpp

📁 用C语言实现进程调度的模拟。通过程序的调试
💻 CPP
字号:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>

typedef struct node 
{
	char name[10];
	int prio;    
	int needtime; 
	char state;   //进程的状态:'M':运行,'R':就绪,'E':结束
	struct node *next; //指向下一个进程的指针  
}PCB;

PCB *end,*ready,*run,*tail; //指向三个队列的队首的指针,tail为就绪队列的队尾指针

int N;

void FirstIn()      //将进程就绪队列中第一个放进就绪队列
{
    if(ready!=NULL)  //ready 就绪 队列不为空
    {
		run=ready;
		ready=ready->next;
		run->state='M';
		run->next=NULL;
	}
	else
	{
		run=NULL;
		
	}
	
}


void display1(char a)  //输出进程信息
{

	printf(" name  needtime  priority  state \n");
  
}


void display2(char a,PCB *p)  //输出单个进程信息
{

	printf("%-10s%-10d%-10d%-5c\n",p->name,p->needtime,p->prio,p->state);

}


void display(char a) //输出所有进程信息
{
	PCB *p;
	display1(a);
	if(run!=NULL)
	{
		display2(a,run);
	}
	
	p=ready;
	while(p!=NULL)
	{
		display2(a,p);
		p=p->next;
	}

	p=end;

	while(p!=NULL)
	{
		display2(a,p);
		p=p->next;
	}
	getchar();   
}


void insert(PCB *q)  //优先级法调度将进程插入到就绪队列算法 ,PCB *q 待插入的队列进程控制块,优先级越高,插入越靠前 

{
	PCB *p,*s,*r;  //p,r用来控制就绪队列滚动,S指向插入的队列
	int b;  //b作为插入控制标志的
	s=q;
	p=ready;
	r=p;
	b=1;
	if(s->prio>=ready->prio)
	{
		s->next=ready;
		ready=s;          
	}
	else
	{
		while((p!=NULL)&&b)
		{
			if(p->prio>=s->prio)
			{
				r=p;
				p=p->next;
			}
			else
			{
				b=0;
			}
		} 
		s->next=p;
		r->next=s;
	}
}



void processInitialize(char algo) //进程初始化
{
	PCB *p;
	int i,time,prio;
	char na[10];
	ready=NULL;
	end=NULL;
	run=NULL;
	for(i=0;i<N;i++)
	{
		p=(PCB*)malloc(sizeof(PCB));
		printf("Enter the name of process\n");
		scanf("%s",na);
		printf("Enter the needtime of process\n");
		scanf("%d",&time);
		printf("Enter the priorty of process\n");
		scanf("%d",&prio);
		strcpy(p->name,na);
		p->needtime=time;
		p->state='R';
		p->prio=prio;
		
		if(ready==NULL)
		{
			ready=p;
			ready->next=NULL;
		}
		else
		{
			insert(p);
		}
		printf("Output the  processes information\n");
		display(algo);
	}
	FirstIn();
}



void priority(char a)//进程调度
{
	
	while(run!=NULL)
	{
		run->needtime-=1;

		run->prio=run->needtime;
		if(run->needtime==0)
		{
			run->next=end;
			end=run;
			run->state='E';
			run=NULL;
			FirstIn();        
		}
		else
		{
			if((ready!=NULL)&&(run->prio<ready->prio))
			{
				run->state='R';
				insert(run);
				run=NULL;
				FirstIn();
			}
		}
		
		display(a);
	}
	
	
}


void main()
{
	char a=0;
	printf("Please enter the number of processes N:");
	scanf("%d",&N);
	processInitialize(a);
	priority(a);
		
}


⌨️ 快捷键说明

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