3、>#include#include#include#defineFIFO"myfifo"#defineN5intlock_var;time_tend_time;charbuf_r[100];定義buf_r數(shù)組表示緩沖區(qū)sem_tmutex,full,empty;互斥信號量木特性,信號量empty表示緩沖池中空幻吃區(qū)適量,full表示滿緩沖區(qū)適量intfd;voidproducer(void*arg);voidconsumer(void*arg);6intma
4、in(intargc,char*argv[]){pthread_tid1,id2;pthread_tmon_th_id;intret;end_time=time(NULL)+10;創(chuàng)建管道if((mkfifo(FIFO,0777
5、O_CREAT)<0)&&(errno!=EEXIST))printf("cannotcreatfifoserver");printf("Preparingforreadingbytes");memset(buf_r,0,sizeof(buf_r));打開管道fd=open(F
6、IFO,O_RDWR
7、O_NONBLOCK,0);if(fd==-1){perror("open");exit(1);}初始化互斥信號和emptyfull緩沖區(qū)ret=sem_init(&mutex,0,1);ret=sem_init(&empty,0,N);ret=sem_init(&full,0,0);if(ret!=0){perror("sem_init");}ret=pthread_create(&id1,NULL,(void*)producer,NULL);創(chuàng)建生產(chǎn)者線程創(chuàng)建成功返回0if(ret!=
8、0)perror("pthreadcreate1");ret=pthread_create(&id2,NULL,(void*)consumer,NULL);創(chuàng)建消費(fèi)者線程創(chuàng)建成功返回0.if(ret!=0)perror("pthreadcreate2");pthread_join(id1,NULL);等待生產(chǎn)者線程結(jié)束pthread_join(id2,NULL);等待消費(fèi)者縣城結(jié)束exit(0);}voidproducer(void*arg){inti,nwrite;while(time(NULL)9、ime){sem_wait(&empty);空緩沖區(qū)的信號量減一6sem_wait(&mutex);互斥信號量減一變?yōu)?。if((nwrite=write(fd,"hello",5))==-1){if(errno==EAGAIN)printf("TheFIFOhasnotbeenreadyet,pleasetrylater");}elseprintf("writehellototheFIFO");sem_post(&full);滿緩沖區(qū)的信號量加一sem_post(&mutex);sleep(1);}}
10、voidconsumer(void*arg){Intnwrite;While(time(NULL)