大连理工大学软件学院操作系统上机实验之生产者与消费者问题

整理文档很辛苦,赏杯茶钱您下走!

免费阅读已结束,点击下载阅读编辑剩下 ...

阅读已结束,您可以下载文档离线阅读编辑

资源描述

#includesys/mman.h#includesys/types.h#includelinux/sem.h#includefcntl.h#includeunistd.h#includestdio.h#includeerrno.h#includetime.h#defineMAXSEM5intfullid;intemptyid;intmutxid;intmain(){structsembufP,V;unionsemunagc;int*array;int*sum;int*set;int*get;array=(int*)mmap(NULL,sizeof(int)*5,PROT_READ|PROT_WRITE,MAP_SHARED|MAP_ANONYMOUS,-1,0);sum=(int*)mmap(NULL,sizeof(int),PROT_READ|PROT_WRITE,MAP_SHARED|MAP_ANONYMOUS,-1,0);get=(int*)mmap(NULL,sizeof(int),PROT_READ|PROT_WRITE,MAP_SHARED|MAP_ANONYMOUS,-1,0);set=(int*)mmap(NULL,sizeof(int),PROT_READ|PROT_WRITE,MAP_SHARED|MAP_ANONYMOUS,-1,0);*sum=0;*get=0;*set=0;fullid=semget(IPC_PRIVATE,1,IPC_CREAT|00666);emptyid=semget(IPC_PRIVATE,1,IPC_CREAT|00666);mutxid=semget(IPC_PRIVATE,1,IPC_CREAT|00666);agc.val=0;if(semctl(fullid,0,SETVAL,agc)==-1)perror(semctlsemvalerror);agc.val=MAXSEM;if(semctl(emptyid,0,SETVAL,agc)==-1)perror(semctlsetvalerror);agc.val=1;if(semctl(mutxid,0,SETVAL,agc)==-1)perror(semctlsemvalerror);V.sem_num=0;V.sem_op=1;V.sem_flg=SEM_UNDO;P.sem_num=0;P.sem_op=-1;P.sem_flg=SEM_UNDO;if(fork()==0){inti=0;while(i20){semop(emptyid,&P,1);semop(mutxid,&P,1);array[*(set)%MAXSEM]=i+1;printf(Producer%d\n,array[(*set)%MAXSEM]);(*set)++;semop(mutxid,&V,1);semop(fullid,&V,1);i++;}sleep(10);printf(Producerisover);exit(0);}else{if(fork()==0){while(1){semop(fullid,&P,1);semop(mutxid,&P,1);if(*get==20)break;*sum+=array[(*get)%MAXSEM];printf(TheConsumerAGetNumber%d\n,array[(*get)%MAXSEM]);(*get)++;if(*get==20)printf(Thesumis%d\n,*sum);semop(mutxid,&V,1);semop(emptyid,&V,1);sleep(1);}printf(ConsumerAisover);exit(0);}else{if(fork()==0){while(1){semop(fullid,&P,1);semop(mutxid,&P,1);if(*get==20)break;*sum+=array[(*get)%MAXSEM];printf(TheConsumerBGetNumber%d\n,array[(*get)%MAXSEM]);(*get)++;if(*get==20)printf(Thesumis%d\n,*sum);semop(mutxid,&V,1);semop(emptyid,&V,1);sleep(1);}printf(ConsumerBisover);exit(0);}}}return0;}

1 / 3
下载文档,编辑使用

©2015-2020 m.777doc.com 三七文档.

备案号:鲁ICP备2024069028号-1 客服联系 QQ:2149211541

×
保存成功