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

📄 timeslice.c

📁 自己的小程序
💻 C
字号:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

typedef struct node     
{
    char name[10];    /*进程名字*/
    int TimeSlice;        /*进程时间轮转时间片*/
    int RunTime;      /*进程占用CPU时间*/
    int RestTime;     /*进程到完成还需要的时间*/
    int count;        /*计数器*/
    struct node *next;  /*链指针*/
}PCB;
PCB *finish,*ready,*tail,*run;  /*各种队列指针*/
int N;
PCB *p;
void PCBcreat()      /*创建进程PCB*/
{
	int i,time,n;
	char Name[10];
	ready=NULL;       /*就绪队列头指针*/
	finish=NULL;      /*完成队列头指针*/
	run=NULL;         /*运行队列指针*/
	printf("Please input TimeSlice:"); /*时间片*/
	scanf("%d",&n);
	for(i=1;i<=N;i++)
	{
		p=malloc(sizeof(PCB));
		printf("Please input the name of process:");
		scanf("%s",Name);
		printf("Please input RunTime:");
		scanf("%d",&time);
		strcpy(p->name,Name);
		p->RunTime=0;
		p->RestTime=time;
		p->count=0;         /*计数器*/
		p->TimeSlice=n;        
		if(ready!=NULL)
		{         /*插入轮转列表*/
			tail->next=p;
			tail=p;
			p->next=NULL;
		}
		else
		{
			p->next=ready;
			ready=p;
			tail=p;
		}
	}
	if(run!=NULL) /*如果运行指针不空*/
	printf("%-8s%",run->name);    /*输出当前正在运行的PCB*/
	/*p=ready;      /*输出就绪队列的PCB*/
	while(p!=NULL)
	{
		p=p->next;
	}
	p=finish;      /*输出就完成队列的PCB*/
	while(p!=NULL)
	{
		p=p->next;
	}
	run=ready;     /*将就绪队列的第一个进程投入运行*/
	ready=ready->next;
}

TimeSlice()      /*时间片轮转实现过程*/
{
	while(run!=NULL)
	{
		if(run!=NULL) /*如果运行指针不空*/
			printf("%-8s",run->name);    /*输出当前正在运行的PCB*/
		run->RunTime=run->RunTime+1;
		run->RestTime=run->RestTime-1;
		run->count=run->count+1;/*运行完将其变为完成态,插入完成队列*/
		if(run->RestTime==0)
		{
			run->next=finish;
			finish=run;
			run=NULL;
			if(ready!=NULL)/*就绪队列不空,将第一个进程投入进行*/
			{
				run=ready;          /*就绪队列头指针赋值给运行头指针*/
				ready=ready->next;  /*就绪队列头指针后移到下一进程*/
			}					
		}
		else if(run->count==run->TimeSlice)   /*如果时间片到*/
		{
			run->count=0;        /*计数器置0*/
			if(ready!=NULL)      /*如果就绪队列不空*/
			{     /*将进程插入到就绪队列中等待轮转*/								
				tail->next=run;
				tail=run;
				run->next=NULL;
				/*将就绪队列的第一个进程投入运行*/
				{
					run=ready;          /*就绪队列头指针赋值给运行头指针*/
					ready=ready->next;  /*就绪队列头指针后移到下一进程*/
				}
			}
		}
		p=ready;      /*输出就绪队列的PCB*/
		while(p!=NULL)
		{
			p=p->next;
		}
		p=finish;      /*输出就完成队列的PCB*/
		while(p!=NULL)
		{
			p=p->next;
		}
		continue;
	}
}
main()
{
	printf("Please input the number of processes:");
	scanf("%d",&N);     /*输入进程数*/       
	PCBcreat();              
	TimeSlice();
}










⌨️ 快捷键说明

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