【操作系统】进程调度
两种调度方式
优先权法 时间片轮转法
#include <bits/stdc++.h>
using namespace std;
int n;
struct node
{
int cpu;
int priority;
int idx=0;
bool operator<(const node &oth)const
{
return oth.priority>priority;
}
};
vector<node> process;
struct state
{
int cputime;
int alltime;
int idx=0;
};
void pt()
{ printf("|----------------------------------------------\n");
for(int i=0;i<n;i++)
{
printf("| 进程编号 %2d ,cpu时间 = %2d ,优先权 = %3d |\n",i+1,process[i].cpu,process[i].priority);
}
printf("|----------------------------------------------\n");
}
void solveA()
{
process.clear();
priority_queue<node>pq;
printf("随机产生的进程:\n");
for(int i=1;i<=n;i++)
{
node tmp; tmp.cpu = rand()%10+1;
tmp.priority = rand()%50+1;
tmp.idx = i;
process.push_back(tmp);
printf("进程编号 %d ,cpu时间 = %d ,优先权 = %d\n",i,tmp.cpu,tmp.priority);
pq.push(tmp);
}
printf("进程调度\n");
while(!pq.empty())
{
node tmp = pq.top();
pq.pop();
tmp.cpu = tmp.cpu-1;
tmp.priority-=3;
process[tmp.idx-1] = tmp;
pt();
if(tmp.cpu>0) pq.push(tmp);
}
}
vector<state>pro;
void pt2()
{
printf("|----------------------------------------------------\n");
for(int i=0;i<n;i++)
{
printf("| 进程编号 %2d ,进程所需时间片 = %2d ,轮转时间片 = %3d |\n",i+1,pro[i].alltime,pro[i].cputime);
}
printf("|----------------------------------------------------\n");
}
void solveB()
{
queue<state>que;
printf("随机产生的进程:\n");
for(int i=1;i<=n;i++)
{
state tmp;
tmp.alltime = rand()%5+10;
tmp.cputime = rand()%10+1;
tmp.idx=i;
printf("进程编号 %d ,进程所需时间片 = %d ,轮转时间片 = %d\n",tmp.idx,tmp.alltime,tmp.cputime);
pro.push_back(tmp);
que.push(tmp);
}
printf("进程调度\n");
while(!que.empty())
{
int t = 0;
state tmp = que.front();
que.pop();
printf("当前进程:%d\n",tmp.idx);
while(t<tmp.cputime)
{
tmp.alltime--;t++;
pro[tmp.idx-1] = tmp;
pt2();
if(tmp.alltime ==0) break;
}
if(tmp.alltime > 0) que.push(tmp);
}
}
int main()
{
srand((unsigned)time(NULL));
cout<<"请输入进程个数"<<endl;
cin>>n;
while(1)
{
int x;
cout<<"请选择进程调度方式"<<endl;
cout<<"优先权法请输入1,轮转法请输入2"<<endl;
cin>>x;
if(x==1) solveA();
else solveB();
}
system("pause");
return 0;
}