⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 shijianpian.cpp

📁 本算法为时间片轮转法
💻 CPP
字号:
#include "stdafx.h"
#include "shijianpian.h"


/*初始化队列*/
LinkQueue::LinkQueue() 
{
	this->front=(PCBQueue)malloc(sizeof(PCB));
	this->rear=this->front;
	if (!this->front) exit (QOVERFLOW);/*存储分配失败*/                   
	this->front->next = NULL;
	totalTime = 0;
	curTime = 0;
	bLastOver = false;
	nZhouzhuanTime = 0;
}

/*销毁队列*/
LinkQueue::~LinkQueue()
{
	while(this->front)
	{
		this->rear= this->front->next;
		free(this->front);
		this->front=this->rear;
	}
}

/*队列长度*/
int LinkQueue::GetLength() const 
{
	int i; 
	i=this->rear-this->front ;
	return i ;
}

/* 队列运行总时间 */
int LinkQueue::GetTotalTime() const
{
	return totalTime;
}

/*叛空*/
bool LinkQueue::IsEmpty() const 
{
	if(this->front-this->rear==0)
		return true;
	else 
		return false;
}

/* 加入预备队列 */
void LinkQueue::SetElemVec( const std::vector<ElemType>& vec )
{
	this->vecElem = vec;
	totalTime = 0;
	for ( QCIT it = this->vecElem.begin(); it != this->vecElem.end(); it++ )
	{
		totalTime += it->cpuTime;
	}
}


/*入队列;插入元素e为新的队尾元素*/
Status LinkQueue::EnQueue( ElemType e) 
{
	PCBQueue p;
	p=(PCBQueue)malloc(sizeof(PCB));
	if(!p)  exit (QOVERFLOW);   /*存储分配失败*/
	p->data=e;  
	p->next=NULL;
	this->rear->next=p;   
	this->rear=p;
	return QOK;
}

/*若队列不空,则删除Q的队头元素,用e返回其值,并返回OK;否则返回ERROR*/
Status LinkQueue::DeQueue( ElemType &e) 
{
	PCBQueue p;
	if (this->front==this->rear) return QERROR;
	p=this->front->next;  
	e=p->data;
	this->front->next=p->next;
	if (this->rear==p)
		this->rear = this->front;
	free (p);
	return QOK;
}


/*判断是否有新进程到达,若有新进程到达,则将其插入队尾*/
std::vector<ElemType>::const_iterator LinkQueue::NewArrive( int iTime , QCIT it_begin)
{
	QCIT it;
	for ( it = it_begin; it != this->vecElem.end(); it++ )
	{
		if ( it->arriveTime == iTime )
			return it;
	}
	return it;
}


/*运行进程*/
Status LinkQueue::RunOnce()
{
	ElemType eTmp1;
	this->bLastOver = false;
	/*判断是否有些进程到达到达插入队尾*/
	QCIT it = NewArrive( this->curTime , vecElem.begin() );
	while ( it != this->vecElem.end() )
	{
		this->EnQueue( *it );
		it++;
		it = NewArrive( this->curTime, it );
	}
	/*对队首进程进行运行*/
	(this->front->next->data.alreadyTime)++;
	(this->front->next->data.needTime)--;
	lastElem = this->front->next->data;

	/*判断仍需时间为0结束进程*/
	if((this->front->next->data.needTime)==0)
	{
		this->bLastOver = true;
		this->nZhouzhuanTime = this->curTime - this->front->next->data.arriveTime;
		this->DeQueue( eTmp1 );
	}
	/*否则插入队列尾*/
	else	
	{
		this->DeQueue( eTmp1 );
		this->EnQueue ( eTmp1 );
	}
	this->curTime++;
	if ( this->GetTotalTime() == this->curTime ) return QOK;
	return QERROR;
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -