模拟时间片轮转调度算法实现(C语言)

模拟时间片轮转调度:

#include <malloc.h>
#include <stdio.h>
#include <string.h>

typedef struct table
{
    int key; /*进程 ID 号*/
    int run_time; /*进程运行时间*/
    char message[10]; /*进程说明信息*/
    struct table *next;
} node;
node *creat(void) /*定义函数,输入 ID 号和顺序号,按照输入次序建立进程链表*/
{
    int x,y,n;
    char str[10];
    printf("输入n的值(n为输入进程个数):\n");
    scanf("%d",&n);
    node *head=(node*)malloc(sizeof(node));
    node *p=(node*)malloc(sizeof(node));
    node *q;
    head->next=NULL;
    p=head;
    while(n--){
        printf("输入key,run_time,message的值:\n");
        scanf("%d%d",&x,&y);
        q=(node*)malloc(sizeof(node));
        q->key=x;
        q->run_time=y;
        for(int i=0;i<10;i++){
            scanf("%c",&str[i]);
            q->message[i]=str[i];
        }
        p->next=q;
        p=p->next;
    }
    p->next=NULL;
    return head;
}
void print (node *head) /*输出链表*/
{
    printf("\nThe Table is:\n");
    node *p=(node*)malloc(sizeof(node));
    p=head->next;
    while(p){
        printf("%d %d ",p->key,p->run_time);
        for(int i=0;i<10;i++)
            printf("%c",p->message[i]);
        printf("\n");
        p=p->next;
    }
}
node *insert(node *head) /*将进程 news 插入到队列尾部*/
{
    if(!head->next->next){
        return head;
    }
    node *p=(node*)malloc(sizeof(node));
    node *q=(node*)malloc(sizeof(node));
    p=head->next;
    q=head->next;
    while(q->next){
        q=q->next;
    }
    head->next=p->next;
    q->next=p;
    q->next->next=NULL;
    return head;
}
node *timeslice(node *head,int cpu_base_time)
/*模拟时间片轮转调度过程:队列首进程使用一个时间片的 CPU*/
{
    node *p=(node*)malloc(sizeof(node));
    p=head->next;
    printf("输出调用进程的进程说明信息:\n");
    for(int i=0;i<10;i++)
        printf("%c",p->message[i]);
    if(p->run_time > cpu_base_time){
        p->run_time-=cpu_base_time;
        head=insert(head);
    }
    else{
        p->run_time=0;
        if(p->next==NULL)
            return NULL;
        else{
            head->next=p->next;
        }
    }
    print(head);
    printf("\n");
    return head;
}
int main()
{
    int count=0,cpu_base_time;
    node *p;
    printf("新建的进程控制表为:\nkey run_time message\n");
    p=creat(); /*输入进程控制表*/
    print(p); /*输出原始进程控制表*/
    printf("\n");
    printf("CPU 运行的单位时间片 cpu_base_time 为:\n");
    scanf("%d",&cpu_base_time);
    printf("\n");
    while(p) /*模拟按单位时间片进程逐个被调度并进入 CPU 运行的过程*/
    {
        p=timeslice(p,cpu_base_time);
    }
    printf("\nThe Table is:\n进程已全部调用\n");
    return 0;
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值