69,373
社区成员
发帖
与我相关
我的任务
分享
#include <iostream>
using namespace std;
extern int s = 3;// 这个是信号量的设置 无所谓了
typedef struct PCB
{
int num;
struct PCB *next;
}PCB,*ready,*stuck;
void Init(PCB *p)
{
p = (PCB*)malloc(sizeof(PCB));
p->next = NULL;
}
ready e; //这里我是没办法才这么写的
stuck k; // 主要是这两个队列的头指针该如何解决!!!!!!!!!!!!!!!!!
void AddR(int ip)
{
if(e->next == NULL) //就在这开始崩溃 ,后面没运行呢
{
PCB *t;
t = (PCB*)malloc(sizeof(PCB)); //如果就绪为空 直接插入
t->num = ip;
t->next = NULL;
e->next = t;
}
else
{
PCB *temp = (PCB*)malloc(sizeof(PCB));
temp->num = ip; //不为空...头插法 后面的加入到阻塞队列的操作和这个类似就不鳌述了
temp->next = e->next;
e->next = temp;
}
}
void weakup(int ip)//这个是唤醒操作 将阻塞队列的一个置到就绪队列
{
PCB *r = k;
PCB *t;
t = r;
while(r->num != ip)//在阻塞队列里找匹配的进程
{
t = r;
r = r->next;
}
t->next = r->next; //从这个队列中出去要找的进程
if(e->next == NULL) //如果队列为空 直接插进去(就绪队列)
{
e->next = r;
e->next = NULL;
}
else //否则...头插法
{
r->next = e->next;
e->next = r;
}
}
void AddS(int ip) //这个是把进程加入到阻塞队列
{
PCB *r = k;
if(r->next == NULL)
{
PCB *t;
t = (PCB*)malloc(sizeof(PCB));
t->num = ip;
t->next = NULL;
r->next = t;
}
else
{
PCB *temp = (PCB*)malloc(sizeof(PCB));
temp->num = ip;
temp->next = r->next;
r->next = temp;
}
}
void P() //p操作
{
int ip;
cout<<"请输入要申请的进程号:";
cin>>ip;
s--;
if(s >= 0)
{
cout<<"分配成功"<<endl;
AddR(ip);
}
else
{
cout<<"分配失败,加入阻塞队列"<<endl;
AddS(ip);
}
}
void V() //V操作
{
int ip;
cout<<"请输入要释放的进程号:";
cin>>ip;
s++;
if(s <= 0)
{
weakup(ip);
}
else
{
if(e->next ==NULL)
cout<<"无法释放,就绪队列为空!"<<endl;
else
{
PCB *t,*pre; //如果部位空 在就绪队列里找出来 删了它!!!
t = e;
pre = t;
t = t->next;
while(t->num != ip);
{
pre = t;
t = t->next;
}
pre->next = t->next;
t->next = NULL;
free(t);
cout<<"进程号为"<<ip<<"资源被释放"<<endl;
}
}
}
int main()
{
Init(e);
Init(k);
int con;
cout<<endl;
cout<<"请选择操作: "<<"1.创建进程,2.结束进程,0.退出"<<endl;;
cout<<"请输入选择:";
cin>>con;
while(con)
{
switch(con){
case 1: P(); break;
case 2: V(); break;
}
}
return 0;
}
void Init(PCB *&p)
{
p = (PCB*)malloc(sizeof(PCB));
p->next = NULL;
}
void Init(PCB **p)
{
*p = (PCB*)malloc(sizeof(PCB));
(*p)->next = NULL;
}
Init(&e);