資源簡介
這是模擬操縱系統中CPU調度問題,調度策略是最短剩余時間優先,聲明只是模擬,并沒有真正的進程調度。
代碼片段和文件信息
#include?
#include?
#include?
typedef?struct
{
int?remain_time; //進程剩余執行時間
int?arrive_time; //進程到達時間
int?Tp; //進入就緒隊列的時間
int?Tc; //進入執行隊列的時間
int?To; //進程執行結束的時間
int?number; //進程編號
}Process_Block; //定義進程模塊
typedef?struct?_Queue
{
Process_Block?PB;
struct?_Queue?*next;
}_Block*Process; //定義一個進程模塊隊列中結點
typedef?struct?
{
Process?head; //隊列頭指針
Process?end; //隊列尾指針
}Process_Queue; //進程隊列
Process_Queue PQ; //定義一個全局隊列變量
int t; //全局時間
Process Run_Now; //當前正在運行的進程,作為全局變量
/*初始化隊列*/
void?InitQueue(Process_Queue?PQ)
{
PQ.head?->next?=?NULL;
PQ.end ->next?=?PQ.head;
}
/*判定隊列是否為空隊列*/
int?IsEmpty(Process_Queue?PQ)
{
if(PQ.end->next?==?PQ.head)
return?1; //隊列空的條件為頭指針指向尾指針并且尾指針指向頭指針
else
return?0;
}
/*插入隊列操作*/
void?EnQueue(Process_Queue?PQProcess?P)
{
Process?temp?=(Process)malloc(sizeof(_Block));
temp?=?PQ.end;
temp->next->next?=?P;
PQ.end->next?=?P;
}
/*出列操作*/
Process?DeQueue(Process_Queue?PQ)
{
if(IsEmpty(PQ))
return?NULL;
Process?temp?=?PQ.head->next;
PQ.head->next=?temp?->next;
if(PQ.end->next?==?temp)
PQ.end->next?=?PQ.head;
return?temp;
}
/*調度最短剩余時間的進程至隊頭*/
Process?ShortestProcess(Process_Queue?PQ)
{
if(IsEmpty(PQ)) //如果隊列為空,返回
{
if(!Run_Now)
return?NULL;
else
return?Run_Now;
}
Process?tempshortestprev;
//temp?=?(Process)malloc(sizeof(_Block));
//shortest?=?(Process)malloc(sizeof(_Block));
int?min_time;
if(Run_Now) //如果當前有進程正在執行,
{
shortest?=?Run_Now; //那么最短進程初始化為當前正在執行的進程,
min_time?=?Run_Now->PB.remain_time;
}
else //如果當前沒有進程執行,
{
shortest?=?PQ.head->next; //則最短進程初始化為隊列中第一個進程
min_time?=?PQ.head->next->PB.remain_time;
}
temp?=?PQ.head;
prev?=?temp;
while(temp->next)
{
if(temp->next->PB.remain_time? {
shortest?=?temp->next; //則保存當前進程,
min_time?=?shortest->PB.remain_time;
prev=temp; //及其前驅
}
temp=temp->next;
}
if(shortest?==?PQ.end->next) //如果最短剩余時間進程是隊列中最后一個進程,
PQ.end->next?=?prev; //則需要修改尾指針指向其前驅
prev->next?=?shortest->next; //修改指針將最短剩余時間進程插入到隊頭
return?shortest;
//shortest->next=PQ.head->next;
//PQ.head->next=shortest;
}
/*運行函數*/
void?Run()
{
Run_Now->PB.remain_time--; //某一時間運行它的剩余時間減1
return;
}
void?Wait()
{
return?;
}
int?sum(int?array[]int?n)
{
int?isum=0;
for(i=0;i sum+=array[i];
return?sum;
}
int?main()
{
PQ.head =?(Process)malloc(sizeof(_Block));
PQ.end =?(Process)malloc(sizeof(_Block));
Run_Now =?(Process)malloc(sizeof(_Block));
Run_Now =NULL;
InitQueue(PQ);
int?iNTotal_Time=0; //Total_Time為所有進程的執行時間之和
printf(“請輸入計算機中的進程數目:“);
scanf(“%d“&N);
Process?*Ptemp;
P?=?(Process*)malloc(
評論
共有 條評論