#include<iostream>
#include<sys/types.h>
#include<sys/ipc.h>
#include<sys/shm.h>
#include<sys/sem.h>
#include<unistd.h>
#include<stdio.h>
#include<errno.h>
#include<math.h>
#include<time.h>
#include<stdio.h>
#include<stdlib.h>
#include<queue>
#include<cstring>
#define N 1000
using namespace std;
int buff;
int fulll;
int *full2;
char *buff1;
void plusORde(int num,int number){
full2[num]=full2[num]+number;
}
void down(int *num)
{
while(true)
{
if(*num>0)
{
*num=*num-1;
break;
}
else{
sleep(1);
}
}
}
void up(int *num)
{
*num=*num+1;
}
char produce_item_low()
{
char ch=((rand() +7)% 26+97);
return ch;
}
char produce_item_lar()
{
char ch=(rand() % 26+65);
return ch ;
}
char remove_item()
{
char ch=buff1[full2[1]-1];
buff1[full2[1]-1]='\0';
down(&full2[1]);
return ch;
}
void printfCharArray(char *chararray,int len){
printf(" flag: %d, len: %d \n",full2[4],len);
}
void insert_item(char x)
{
char xx[2];
xx[0]=x;
xx[1]='\0';
strcat(buff1,xx);
up(&full2[1]);
}
void consume_item(char item)
{
printf("\n remove:%c ",item);
printfCharArray(buff1,full2[1]);
}
void producer(int flag)
{
char item;
while (true)
{
if(full2[4]>200)
sleep(1);
switch(flag)
{
case 1:
item = produce_item_lar();
break;
case 2:
item = produce_item_low();
break;
};
down(&full2[2]);
down(&full2[0]);
insert_item(item);
up(&full2[0]);
up(&full2[3]);
full2[4]++;
printf("\n produce:%c ",item);
printfCharArray(buff1,full2[1]);
}
}
void consumer()
{
char item;
while (true)
{
if(full2[4]>200)
sleep(1);
down(&full2[3]);
down(&full2[0]);
item = remove_item();
up(&full2[0]);
up(&full2[2]);
full2[4]++;
consume_item(item);
}
}
int main()
{
fulll=shmget(IPC_PRIVATE,1024,IPC_CREAT|0666);
buff=shmget(IPC_PRIVATE,1024,IPC_CREAT|0666);
full2=(int*)shmat(fulll,0,0);
buff1=(char*)shmat(buff,0,0);
full2[0]=1;
full2[1]=0;
full2[2]=N;
full2[3]=0;
full2[4]=0;
if(fork()==0)
consumer();
else
if(fork()==0)
producer(1);
else
if(fork()==0)
consumer();
else
if(fork()==0)
consumer();
else
producer(2);
semctl(buff,IPC_RMID,0);
semctl(fulll,IPC_RMID,0);
return 0;
}