操作系统实验六——死锁问题实验

实验内容:
在两个城市南北⽅向之间存在⼀条铁路,多列⽕⻋可以分别从两个城市的⻋站 排队等待进⼊⻋道向对⽅
城市⾏驶,该铁路在同⼀时间,只能允许在同⼀⽅向上⾏⻋,如果同时有相向的⽕⻋⾏驶将会撞⻋。请
模拟实现两个⽅向⾏⻋,⽽不会出现撞⻋或⻓时间等待的情况。您能构造⼀个管程来解决这个问题吗?

dp.h

#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <sys/sem.h>
#include <sys/msg.h>
#include <sys/wait.h>
#include<time.h>
using namespace std;

/*信号灯控制用的共同体*/
typedef union semuns { int val; } Sem_uns;

enum State {waitt,run};

//火车站管程中使用的信号量
class Sema{
	public:
		Sema(int id);
		~Sema();
		int down(); //信号量加 1
		int up(); //信号量减 1
	private:
		int sem_id; //信号量标识符
};

//火车站管程中使用的锁
class Lock{
	public:
		Lock(Sema *lock);
		~Lock();
		void close_lock();
		void open_lock();
	private:
		Sema *sema; //锁使用的信号量
};

//火车站管程中使用的条件变量
class Condition{
	public:
		Condition(char *st[], Sema *sm);
		~Condition();
		void Wait(Lock *lock,int i); //条件变量阻塞操作
		void Signal(int i); //条件变量唤醒操作
	private:
		Sema *sema;
		char **state;
};

//火车站管程的定义
class dp{
	public:
        int *maxcars;//最大火车数
        int *nowcars;//当前已经通过的火车数
        
        int *sumeast;//当前已经通过的由东向西的火车数
        int *sumwest;//当前已经通过的由西向东的火车数

		dp(int rate,int maxcur); //管程构造函数
		~dp();
		void start(int i); //发车
		void quit(int i); //火车通过后离开

		//建立或获取 ipc 信号量的一组函数的原型说明
		int get_ipc_id(char *proc_file,key_t key);
		int set_sem(key_t sem_key,int sem_val,int sem_flag);
		char *set_shm(key_t shm_key,int shm_num,int shm_flag);
	private:
		int rate ;//车速
		Lock *lock; 
		char *state[2];//两个火车站的状态
		int cnt[2];//火车站同时发送火车的数量
		Condition *self[2];//火车站条件变量
};

dp.cc

#include "dp.h"
//分别是由东向西,由西向东的车辆数和单方向火车站同时最多能发的车辆数
int eastsum,westsum,d_maxcar;

Sema::Sema(int id){sem_id = id;}
Sema::~Sema(){ }
/*
* 信号灯上的 down/up 操作
* semid:信号灯数组标识符
* semnum:信号灯数组下标
* buf:操作信号灯的结构
*/
int Sema::down()
{
	struct sembuf buf;
	buf.sem_op = -1;
	buf.sem_num = 0;
	buf.sem_flg = SEM_UNDO;
	if((semop(sem_id,&buf,1)) <0)对semid执行buf操作
	{
		perror("down error ");
		exit(EXIT_FAILURE);
	}
	return EXIT_SUCCESS;
}

int Sema::up()
{
	Sem_uns arg;
	struct sembuf buf;
	buf.sem_op = 1;
	buf.sem_num = 0;
	buf.sem_flg = SEM_UNDO;
	if((semop(sem_id,&buf,1)) <0)
	{
		perror("up error ");
		exit(EXIT_FAILURE);
	}
	return EXIT_SUCCESS;
}

Lock::Lock(Sema * s){sema = s;}
Lock::~Lock(){ }
//上锁
void Lock::close_lock(){sema->down();}
//开锁
void Lock::open_lock(){sema->up();}

Condition::Condition(char *st[] ,Sema *sm)
{
	state = st;
	sema = sm;
}

void Condition::Wait(Lock *lock,int i)
{
	if((*state[i^1] == waitt))//对面没发车
			*state[i] = run;//发车
	else
	{
		lock->open_lock();
		sema->down();
		lock->close_lock();
	}
}

void Condition::Signal(int i)
{
	if((*state[i^1] == waitt) &&(*state[i] == waitt))
	{ //可发车
		sema->up();
		*state[i] = run;
	}
}

int dp::get_ipc_id(char *proc_file,key_t key)
{
	#define BUFSZ 256
	FILE *pf;
	int i,j;
	char line[BUFSZ],colum[BUFSZ];
	if((pf = fopen(proc_file,"r")) == NULL)读文件
	{
		perror("Proc file not open");
		exit(EXIT_FAILURE);
	}
	fgets(line, BUFSZ,pf);
	while(!feof(pf))
	{
		i = j = 0;
		fgets(line, BUFSZ,pf);
		while(line[i] == ' ') i++;
		while(line[i] !=' ') colum[j++] = line[i++];
		colum[j] = '\0';
		if(atoi(colum) != key) continue;
		j=0;
		while(line[i] == ' ') i++;
		while(line[i] !=' ') colum[j++] = line[i++];
		colum[j] = '\0';
		i = atoi(colum);
		fclose(pf);
		return i;
	}
	fclose(pf);
	return -1;
}

int dp::set_sem(key_t sem_key,int sem_val,int sem_flg)
{
	int sem_id;
	Sem_uns sem_arg;
	if((sem_id=get_ipc_id((char*)"/proc/sysvipc/sem",sem_key)) < 0 )
	{
		if((sem_id = semget(sem_key,1,sem_flg)) < 0)
		{
			perror("semaphore create error");
			exit(EXIT_FAILURE);
		}
	}
	sem_arg.val = sem_val;
	if(semctl(sem_id,0,SETVAL,sem_arg) < 0)
	{
		perror("semaphore set error");
		exit(EXIT_FAILURE);
	}
	return sem_id;
}

char * dp::set_shm(key_t shm_key,int shm_num,int shm_flg)
{
	int i,shm_id;
	char * shm_buf;
	if((shm_id=get_ipc_id("/proc/sysvipc/shm", shm_key))<0)
	{
		if((shm_id= shmget(shm_key,shm_num,shm_flg)) <0)
		{
			perror("shareMemory set error");
			exit(EXIT_FAILURE);
		}
		if((shm_buf=(char *)shmat(shm_id,0,0)) < (char *)0)
		{
			perror("get shareMemory error");
			exit(EXIT_FAILURE);
		}
		for(i=0; i<shm_num; i++) shm_buf[i] = 0;
	}
	if((shm_buf = (char *)shmat(shm_id,0,0)) < (char *)0)
	{
		perror("get shareMemory error");
		exit(EXIT_FAILURE);
	}
	return shm_buf;
}

dp::dp(int r,int maxcur)
{
	int ipc_flg = IPC_CREAT | 0644;
	int shm_key = 220;
	int shm_num = 1;
	int sem_key = 120;
	int sem_val = 0;
	int sem_id;
	Sema *sema;
	rate = r;
	//位变量创建共享内存
	maxcars=(int *) set_shm(sem_key++, 1, ipc_flg);
	nowcars=(int *) set_shm(sem_key++, 1, ipc_flg);
	sumeast=(int *) set_shm(sem_key++, 1, ipc_flg);
	sumwest=(int *) set_shm(sem_key++, 1, ipc_flg);
	//初始化
	*maxcars=maxcur;
	*nowcars=0;
	*sumeast=0;
	*sumwest=0;
	//创建管程中的锁和条件变量
	if((sem_id = set_sem(sem_key++,1,ipc_flg)) < 0)
	{
		perror("Semaphor create error");
		exit(EXIT_FAILURE);
	}
	sema = new Sema(sem_id);
	lock = new Lock(sema);
	for(int i=0; i<=1; i++)
	{
		if((state[i]=(char *)set_shm(shm_key++,shm_num,ipc_flg)) == NULL)
		{
			perror("Share memory create error");
			exit(EXIT_FAILURE);
		}
		*state[i]=waitt;
		if((sem_id = set_sem(sem_key++,sem_val,ipc_flg)) < 0)
		{
			perror("Semaphor create error");
			exit(EXIT_FAILURE);
		}
		sema = new Sema(sem_id);
		self[i] = new Condition(state,sema);
	}
}

void dp::start(int i)
{
	lock->close_lock();
	//测试能否发车
	self[i]->Wait(lock,i);

	if(i==0)
	{
		*sumeast=*sumeast+1;
		cout << "火车站" << getpid() << "发送火车由东向西"<<*nowcars<<"\n";
	} 
	else if(i==1)
	{
		*sumwest=*sumwest+1;
		cout << "火车站" << getpid() << "发送火车由西向东"<<*nowcars<<"\n";
	}
	//
	
	*nowcars=*nowcars+1;
	cnt[i]=cnt[i]+1;
	//模拟发送火车的时间
	sleep(rate);
	lock->open_lock();
}
//火车正常通过,离开
void dp::quit(int i)
{
	lock->close_lock();
	if(i==0)
	{
		if((cnt[0]==d_maxcar||*sumeast==eastsum))
		{
			if(*sumwest<westsum)
			{
				cnt[0]=0;
				*state[0]=waitt;
				self[1]->Signal(1);
				if(*sumeast<eastsum)cout << "火车站"<< getpid() << "等待\n";
				else cout << "火车站"<< getpid() << "结束发车\n";
			}
			else if(*sumeast<eastsum)
			{
				cout << "火车站"<< getpid() << "继续发车\n";
			}
			else
			{
				cout << "火车站"<< getpid() << "结束发车\n";
			}
		}
		else
		{
			cout << "火车站"<< getpid() << "继续发车\n";
		}
	}
	else if(i==1)
	{
		if((cnt[1]==d_maxcar||*sumwest==westsum))
		{
			if(*sumeast<eastsum)
			{
				cnt[1]=0;
				*state[1]=waitt;
				self[0]->Signal(0);
				if(*sumwest<westsum) cout << "火车站"<< getpid() << "等待\n";
				else cout << "火车站"<< getpid() << "结束发车\n";
			}
			else if(*sumwest<westsum)
			{
				cout << "火车站"<< getpid() << "继续发车\n";
			}
			else
			{
				cout << "火车站"<< getpid() << "结束发车\n";
			}
		}
		else
		{
			cout << "火车站"<< getpid() << "继续发车\n";
		}

	}
	lock->open_lock();
}
dp::~dp(){ }
int main(int argc,char *argv[])
{
	int maxcur;
	cout<<"请输入火车的数量:";
	cin>>maxcur;
	cout<<"请输入单方向同时最多发送的火车数";
	cin>>d_maxcar;

	dp *tdp;
	int pid[2];
	int rate ;
	rate = (argc > 1) ? atoi(argv[1]) : 2 ;
	tdp = new dp(rate,maxcur);

	for(int i=0;i<maxcur;i++)
	{
		if(rand()%2==0)eastsum++;
		else westsum++;
	}
	cout<<eastsum<<' '<<westsum<<endl;

	for(int i=0;i<=1;i++)
	{
		pid[i]=fork();
		if(pid[i]==0){
			while(1)
			{
				//cout<<*tdp->sumeast<<" "<<*tdp->sumwest<<endl;
				tdp->start(i);
				tdp->quit(i);
				if(i==0&&*tdp->sumeast==eastsum)break;
				else if(i==1&&*tdp->sumwest==westsum)break;
			}
			exit(0);
		}
	}
	for(int i=0;i<2;i++)
	{
		waitpid(pid[i],NULL,0);
	}
	return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值