- #define NULL 0
- #include <iostream>
- #include <string>
- using namespace std;
- typedef struct pcb //进程控制块
- {
- string pname;
- int pnum;
- int runtime;
- int priority;
- char state;
- struct pcb * next;
- }PCB;
- PCB *head; //进程链表头指针
- PCB *run_process; //指向正在运行的进程
- static R = 'r', C = 'c';
- int needtime[5];
- void InputProcess() //进程输入函数
- {
- PCB *p ;
- head = new PCB;
- p = head;
- for(int i = 0; i < 5; i++)
- {
- cin>>p->pname>> p->runtime >> p->priority ;
- p->state = R;
- p->pnum = i;
- needtime[p->pnum] = p->runtime;
- if(i != 4)
- {
- p->next = new PCB;
- p = p->next;
- }
- else
- {
- p->next = NULL;
- }
- }
- } //输入5个进程的进程名,估计运行时间和优先级
- void RunProcess() //进程运行函数
- {
- PCB *p1,*p2,*p3;
- p3 = p1 = run_process;
- p2 = head;
- p1->priority++; //优先级+1
- p1->runtime--; //运行时间-1
- if(p1->runtime <= 0) //如果运行完成,状态改成C
- {
- p1->state = C;
- }
- cout<<"刚运行的进程:"<<endl;
- cout<<"进程名: "<< p1->pname<<" "<<"优先级: "<<p1->priority
- <<" "<<"剩余时间: "<<p1->runtime<<" "<<"已运行时间: "
- <<needtime[p1->pnum] - p1->runtime<<" "<<"状态: "<<p1->state<<endl;
- if(p1->runtime <= 0) //如果进程运行完成,从链表中删除
- {
- if(head == p1)
- {
- head = head->next;
- }
- else
- {
- while(p2->next != p1 )
- {
- p2 = p2->next;
- }
- p2->next = p1->next;
- }
- run_process = head;
- }
- p1 = head;
- if(p1 != NULL)
- {
- cout<<"就绪队列中的进程:"<<endl;
- }
- while(p1 != NULL) //输出就绪队列中的进程情况
- {
- if(p1 != p3)
- {
- cout<<"进程名: "<<p1->pname<<" "<<"优先级: "<<p1->priority
- <<" "<<"剩余时间: "<<p1->runtime<<" "<<"已运行时间: "
- <<needtime[p1->pnum] - p1->runtime<<" "<<"状态: "<<p1->state<<endl;
- }
- p1 = p1->next;
- }
- cout<<endl;
- }
- int readydata() //判断就绪队列是否为空,不为空则选择优先级高(数字低)
- { //的进程运行
- PCB *p3;
- p3 = head;
- if(head == NULL)
- {
- return 0;
- }
- else if(head->next == NULL)
- {
- run_process = head;
- return 1;
- }
- else
- {
- if(run_process == NULL)
- {
- run_process = head;
- }
- while(p3 != NULL)
- {
- if(run_process->priority > p3->priority)
- {
- run_process = p3;
- }
- p3 = p3->next;
- }
- return 1;
- }
- }
- int main()
- {
- int m;
- cout<<"请输入5个进程名及其估计运行时间和优先级:"<<endl;
- cout<<"进程名 运行时间 优先级"<<endl;
- InputProcess(); //输入进程
- while((m = readydata()) != 0) //选择就绪队列中的进程
- {
- RunProcess(); //运行进程
- }
- }