您好,欢迎访问三七文档
当前位置:首页 > 商业/管理/HR > 经营企划 > 大连理工大学软件学院操作系统上机实验之生产者与消费者问题
#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;}
本文标题:大连理工大学软件学院操作系统上机实验之生产者与消费者问题
链接地址:https://www.777doc.com/doc-6058816 .html