#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
#include <windows.h>
#define NULL 0
struct spcb {
char name;
char state;
char why;
int dd
};
typedef struct spcb pcb;
pcb producter,consumer,*process,*process1;
int s1,s2,i,j,in,out,pc,m;
char array[10];
char c,x;
int pa[6],sa[6];
int p(int s) /* p操作原语 */
{
s=s-1;
if(s<0)
{
process->state='B'; /* B表示阻塞*/
process->why='s';
}
else
{
process->state='W'; /* W表示就绪*/
}
return(s);
}
int v(int s) /*v操作原语*/
{
s=s+1;
if(s<=0)
{
process1->state='W';
}
process->state='W';
return(s);
}
char RanChar()
{
char arr[10]={'a','b','c','d','e','f','g','h','i','j'};
return arr[abs(rand()%10)];
}
void put()
{
// printf("\n please product anychar!");
// scanf("\n%c",&c); Sleep(1000);
array[in]=RanChar(); in=(in+1)%10;
printf(" product a char is %c!\n ",array[in-1]);
int k = 0;
for(m=0;m<10;m++)
{
if (array[m]!=' ')
{
printf("%c",array[m]);
k = k+1;
}
}
printf("缓冲池中有%d个产品\n",k); }
void get()
{
Sleep(1000);
x=array[out];
printf("\n%c get a char fron buffer",x);
printf("\n"); array[out]=' ';
out=(out+1)%10;
int k = 0;
for(m=0;m<10;m++)
{
if (array[m]!=' ')
{
printf("%c",array[m]);
k = k+1;
}
}
printf("缓冲池中有%d个产品\n",k); }
void gotol()
{
pc=0;
}
void nop()
{;}
void disp() /*建立进程显示函数,用于显示当前进程*/
{
printf("\n name \t state \t why \t dd \n");
printf("|%c\t",process->name);
printf("|%c\t",process->state);
printf("|%c\t",process->why);
printf("|%d\t",process->dd); printf("\n");
}
void init()/*初始化程序*/
{
s1=10;/*s1表示空缓冲区的数量*/
s2=0; /*s2表示满缓冲区的数量*/
producter.name='p';/*对生产者进程初始化*/
producter.state='W';
producter.why=' ';
producter.dd=0;
consumer.name='c';/*对消费者进程初始化*/
consumer.state='W';
consumer.why=' ';
consumer.dd=0;
for(int k=0;k<10;k++)
{
array[k] = ' ';
}
}
void bornpa() /*将生产者程序装入pa[]中*/
{
for(i=0;i<=3;i++)
{
pa[i]=i;
}
}
void bornsa()/*将消费者程序装入sa[]中*/
{
for(i=0;i<=3;i++)
{
sa[i]=i;
}
}
void diaodu()/*处理器调度程序*/
{
while((producter.state=='W')||(consumer.state=='W'))
{
x=rand();/*x随机获得一个数*/
x=x%2;/*对X取于*/
if(x==0)/*若X等于零,则执行生产者进程,反之执行消费者进程*/
{
process=&producter;/*process表示现行进程,将现行进程置为生产者进程*/
process1=&consumer;
}
else
{
process=&consumer;
process1=&producter;
}
pc=process->dd;
i=pc;/*此时把PC的值付给I*/
if((process->name=='p')&&(process->state=='W'))
{
j=pa[i];
pc=i+1;
switch(j)
{
case 0:
s1=p(s1);
process->dd=pc;
break;
case 1:
put();
process->state='W';
process->dd=pc;break;
case 2: s2=v(s2);
process->dd=pc;break;
case 3:
gotol();
process->state='W';
process->dd=pc;
}
}
else if((process->name=='c')&&(process->state=='W'))/*执行消费者进程且该进程处于就绪状态*/
{
process->state='W';
j=sa[i];
pc=i+1;
switch(j)
{
case 0:
s2=p(s2);
process->dd=pc;break;/*申请资源,若没有申请到则跳转*/
case 1:
get();
process->dd=pc;break;
case 2:
s1=v(s1);
process->dd=pc;break;
case 3: gotol();process->state='W';
process->dd=pc;
}
} /*end else*/
}/*end while*/
printf("\nThe program is over!\n"); }
void main()
{
init();
bornpa();
bornsa();
diaodu();
}