资源简介
模拟动态分区的分配以及回收 ,首次适应算法,循环首次适应算法以及最佳适应算法。
代码片段和文件信息
#include
#include
#include
using namespace std;
struct memory
{
struct memory *former;
int address;//地址
int num;//作业号
int size;//分配内存大小
int state;//状态0表示空闲1表示已分配
struct memory *next;
};
typedef struct memory MEMORY;
MEMORY *mem;
const int size_min=10;//内存允许的最小空闲块的大小
bool is_optimist=false;//判断是否是最佳适应算法
void init();
void FF();
void alloc(MEMORY *MEMORY *);//首次适应算法分配内存
void free(MEMORY *);//首次适应算法回收内存
void sort(MEMORY *);//对内存链进行排序
void insert(MEMORY *MEMORY *);
void free_optimist(MEMORY *);
void print(MEMORY *);//打印内存链
void main()
{
int i=0;
while(1)
{
cout<<(“\nPlease select a number(120)“);
cout<<(“\n 1--首次适应算法“);
cout<<“\n 2--最佳适应算法“< cout<<“ 0--中止程序“< cin>>i;
if(i==1)
{
cout<<(“\nThis is an example for FF:\n“);
is_optimist=false;
init();
FF();
}
else if(i==2)
{
cout<<“\nThis is an example for optimist method;\n“;
is_optimist=true;
init();
FF();
}
else if(i==0)
{
exit(1);
}
}
}
void init()
{
mem=new MEMORY;
mem->size=640;
//mem->state=0;
mem->former=0;
mem->next=0;
}
void FF()//首次适应算法
{
int i;
int work[]={130601002001406050};//作业序列
//int assignment;
MEMORY *running;
for(i=0;i {
running=(MEMORY *)malloc(sizeof(MEMORY));//初始化作业
if(running!=NULL)
{
running->former=NULL;
running->address=0;
running->num=i+1;
running->size=work[i];
running->state=0;
running->next=NULL;
//cout<<“作业初始化成功“<num< if(is_optimist==true)//最佳适应算法
{
//cout<<“xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx“< alloc(memrunning);
}
else//首次适应算法
{
alloc(memrunning);
}
print(mem);
cout< }
else
cout<<“没有足够的内存空间“<
if(rand()%3==1)
{
if(is_optimist==false)//首次适应算法
{
free(mem);
}
else//最佳适应算法
{
::free_optimist(mem);
}
}
}
}
void free(MEMORY *ptr)//作业处理完后释放内存空间
{
MEMORY *previous*current;
previous=ptr;
current=previous->next;
while(current!=NULL)
{
if(current->state==1&&rand()%3==1)
{
break;
}
previous=current;
current=current->next;
}
if(current==NULL)
{
//cout<<“内存中没有任何作业!!!“< return;
}
else if(current->next==NULL)
{
if(previous->state==0)
{
MEMORY *temp;
temp=current;
previous->size=previous->size+current->size;
previous->next=NULL;
cout<<“作业 “<<(current->num)<<“释放 “<<(current->size)<<“k 的空间“< delete temp;
print(mem);
}
else
{
current->state=0;
cout<<“作业 “<<(current->num)<<“释放 “<<(current->size)<<“k 的空间“< print(mem);
}
}
else if((current->next)->next==NULL)
{
if(previous->state==0&&(current->
评论
共有 条评论