资源描述:
《生产者消费实验.doc》由会员上传分享,免费在线阅读,更多相关内容在行业资料-天天文库。
1、生产者消费者实验程序实现了两个生产者和两个消费者的生产者消费者问题(当生产者消费者数目再多时加上几个子进程就可以了)为了防止程序陷入死循环,给生产者限定了生产次数,同时为了方便截图,将次数限定的比较少。下面是我的程序:#include#include#include#include#include#include
#include
#include
#include
#i
2、nclude
#defineBSIZE8
typedefstruct
{
intbuffer[BSIZE];
sem_tlock;
sem_tnready;
sem_tnempty;
intindex;//nexttoput,nextgetisindex-1
}shared_t;
intget_one_item(shared_t*ptr)
{
intrval;
sem_wait(&ptr->nready);
sem_wait(&ptr->lock);
rval=ptr->buffer[--ptr->index];
sem_post(&ptr-
3、>lock);
sem_post(&ptr->nempty);
returnrval;
}
intput_one_item(shared_t*ptr,intpval)
{
sem_wait(&ptr->nempty);
sem_wait(&ptr->lock);
ptr->buffer[ptr->index++]=pval;
sem_post(&ptr->lock);
sem_post(&ptr->nready);
returnpval;
}
voiderr_quit(char*msg)
{
fprintf(stderr,"%s:%s",msg,stre
4、rror(errno));
exit(1);
}
intmain(void)
{
pid_tpid;
intj;
shared_t*ptr;
ptr=mmap(NULL,sizeof(shared_t),PROT_READ
5、PROT_WRITE,MAP_SHARED
6、MAP_ANONYMOUS,-1,0);
if((int)ptr==-1)
err_quit("mmaperror");
sem_init(&ptr->lock,1,1);/*sharedbetweenprocess,init-value=1*/
sem_init(&ptr->nready,1,
7、0);
sem_init(&ptr->nempty,1,BSIZE);
setbuf(stdout,NULL);
//ptr->a=10;
pid=fork();
if(pid<0)
err_quit("forkerror");
elseif(pid==0)
{/*child第一个子进程,作为第一个消费者*/
sleep(2);
while(1)
{
printf("firstprocess%dgetvalue:%d",getpid(),get_one_item(ptr));
usleep(300*1000);
}
}
else
{
intpid1=fo
8、rk();/*第二个子进程,作为第二个消费者*/
if(pid1<0)
err_quit("forksecondprocesserror");
elseif(pid1==0)
{
sleep(3);
while(1)
{
printf("secondprocess%dgetvalue:%d",getpid(),get_one_item(ptr));
usleep(300*1000);
}
}else
{
intpid2=fork();/*第三个子进程,作为生产者*/
if(pid2<0)
err_quit("forkthirdprocesserror")
9、;
elseif(pid2==0)
{
srand(time(NULL));
intval=0;
for(j=0;j<5;j++)
//while(ptr->a)
{
val=1+rand()%1000;
printf("thirdprocessputvalue:%d",put_one_item(ptr,val));
usleep(300*1000);
//(ptr->a)--;
}
}
else/*父进程,生产者*/
{
sleep(1);
srand(time(NULL));
intpval=0;
//while(ptr->a)//
for(j=0
10、;j<5;j++)
{
pval=1+rand()%