时间片轮转算法模拟

4 篇文章 0 订阅

这是我们操作系统课程设计的时候写的一个模拟时间片轮转的算法。比较简单。哈哈哈哈

代码如下:

/*时间片轮转算法
 author GODLUO
 1.获取用户输入
 2.创建结构体并且插入链表
 3.时间片循环消耗进程中时间
  3.1时间够直接减去
  3.2时间不够一个时间片,按进程剩余时间
 4.结束,输出一共所用时间以及各进程所用
   时间和各进程结束顺序
 */
#include<stdio.h>
#include<stdlib.h>
#include<windows.h>
int slice=1;//时间片段为一秒
float totaltime=0;//用来记录总的时间
float totalcycletime=0;//带权周转时间和
typedef struct pcb
{
	char name;
    float needtime;//用户输入的所用时间
	float spenttime;//计算中得到的时间
	float cycletime;//带权周转时间
    struct pcb *next;
}PCB;
void createlist(PCB *&,int );
void timeslice(PCB *&,int );
int main()
{
	//调整窗口大小和位置
    system("mode con cols=50 lines=50");
    int a;//接受用户输入进程数
    PCB *L;//指向链表的指针
    printf("请输入进程数\n");
    scanf("%d",&a);
    //创建链表并将进程插入
    createlist(L,a);
	timeslice(L,a);
    return 0;
}
//创建链表
void createlist(PCB* &L,int n)
{
 PCB *a,*b;
 L=(PCB*)malloc(sizeof(PCB));
 L->next=NULL;
 a=L;
 int i;
 for(i=1;i<=n;i++)
 {
  b=(PCB*)malloc(sizeof(PCB));
  int z=getchar();//将缓冲区的回车字符取出
  printf("请输入第%d个进程的名字\n",i);
  scanf("%c",&b->name);
  printf("请输入%c进程的时间\n",b->name);
  scanf("%f",&b->needtime);
  b->spenttime=0;//赋初值
  b->cycletime=0;//周转时间赋初值
  a->next=b;
  a=b;
 }
 a->next=L->next;//构成循环链表
}
//时间片轮转
void timeslice(PCB* &L,int n)
{
 int p=n;
 PCB *a,*b;
 a=L->next;
 b=L;//b指针是为了删除进程时用
 while(n!=0)
 {
  if(a->needtime>slice)
  {
	  a->needtime-=slice;
	  totaltime+=slice;
	  a->spenttime+=slice;
	  printf("%c进程运行中\n",a->name);
	  Sleep(1000);//等待一个时间片
	  a=a->next;
	  b=b->next;
  }
  else if(a->needtime<slice||a->needtime==slice)
  {
      a->spenttime+=a->needtime;
	  totaltime+=a->needtime;
	  a->cycletime=totaltime/a->spenttime;
	  totalcycletime+=a->cycletime;
	  printf("进程%c结束,所用的时间为%f秒,周转时间为%f秒,带权周转时间为%f秒\n",a->name,a->spenttime,totaltime,a->cycletime);
	  Sleep((a->needtime)*1000);
	  //从链表中删除该进程
      b->next=a->next;
	  free(a);
	  a=b->next;
	  n-=1;
  }
 }
 float z=totalcycletime/p;
 printf("所有进程结束,总时间为%f秒,平均带权周转时间为%f秒\n",totaltime,z);
 
}

 

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值