基于信号量机制的进程同步问题模拟程序

背景:在多任务系统中,进程之间的相互影响成为必须解决的重要问题,由于共享资源争抢(间接制约)和进程之间的固有协作关系(直接制约),导致进程之间存在相互制约关系。1965年荷兰学者Dijkstra提出的信号量机制是用于解决进程间同步问题的一种重要机制。
问题描述:在父亲、女儿和儿子面前有一个放置水果的盘子plate,盘子最多可以放6个水果。父亲随机地向盘子里放入水果,可能是苹果也可能是桔子。女儿和儿子从盘 子中拿水果吃,但是女儿只吃桔子orange,儿子只吃苹果apple,并且每次只能有一个人对盘子访问(放水果或者拿水果)。
这是操作系统课上的第三次作业吧,晚上做了一下,只是个模拟程序,还不够完善。
#define RUNNING     0  
#define READY       1  
#define BLOCK	    2
#define FATHER		9
#define SON			8
#define DAUGHTER	7 
#include <stdio.h>
#include <time.h>
#include <stdlib.h>
typedef struct PCB
{
	int pid;//进程的标识号
	int pstatus;//进程的状态
	struct PCB * next;//指向下一个进程的指针
}PCB;

/* 信号量定义 */
typedef struct semaphore 
{
	int value;//初始为0
	int id;//0表示orange,1表示apple,2表示空
	PCB *bqhead;
}semaphore;

/* 阻塞函数 */
void block(PCB *process)
{
	/* 将进程阻塞 */
	/* 将函数状态修改为阻塞态,保证main函数调度的时候不会调度阻塞状态的函数运行 */
	process->pstatus=2;//阻塞态
	if(process->pid==9)
		printf("Father block!\n");
	if(process->pid==8)
		printf("Son block!\n");
	if(process->pid==7)
		printf("Daughter block!\n");
}

/* 唤醒函数 */
void wakeup(PCB *process)
{
	/* 唤醒进程  */
	/* 将函数状态修改为就绪态,main函数调度的时候会调度就绪状态的函数运行 */
	process->pstatus=1;//就绪态
	if(process->pid==9)
		printf("Father wakeup!\n");
	if(process->pid==8)
		printf("Son wakeup!\n");
	if(process->pid==7)
		printf("Daughter wakeup!\n");
}

/* wait操作 */
void wait(semaphore *s)
{
	s->value--;
	if (s->value<0) {
		block(s->bqhead);
	}
}

/* signal操作 */
void signal(semaphore *s)
{
	s->value++;
	if (s->value<=0) {
		wakeup(s->bqhead);
	}
}

int main()
{
	int count=0;
	semaphore *s;
	PCB *pcb;
	s=(semaphore *)malloc(sizeof(semaphore));
	s->value=0;s->id=2;
	pcb=(PCB *)malloc(sizeof(PCB));
	pcb->pstatus=1;//初始化状态为就绪态
	srand((unsigned)time(NULL));//产生一个随机种子
	while(count!=20){
		int i = rand() % 3+7 ;//在7-9中随机产生一个数,即从
		pcb->pid=i;
		if(s->value<=6 && pcb->pstatus!=2){
			if(pcb->pid==9 )//父亲放水果
			{
				s->id=rand()%2;//产生0或1表示放入的水果为橘子或苹果
					signal(s);
				if(s->id==1)
					printf("Father put an Apple!\n");				
				else if(s->id==0)
					printf("Father put an Orange!\n");
			}
		}
		if (s->value>0 && pcb->pstatus!=2)
		{
				
				if(s->id==1 && pcb->pid==8)//苹果
				{
					wait(s);
					printf("Son pick an Apple!\n");
				}
				else if(s->id==0&&pcb->pid==8)//橘子
				{
					printf("Son don't like Orange\n");
				}
				else if(s->id==0&&pcb->pid==9)//苹果
				{
					wait(s);
					printf("Daughter pick an Orange!\n");
				}
				else if(s->id==1&&pcb->pid==9)//橘子
					printf("Daughter don't like Apple!\n");
		}
		else{
				int k=rand() % 2+1;//1-2
				switch(k){
				case 1:	
					block(pcb);break;
				case 2:
					wakeup(pcb);break;
				}
		}		
		count++;//统计循环次数
	}
	return 0;
}


你可能感兴趣的:(Semaphore,Semaphore,Signal)