#include
sem_tmutex,full,avail;/*定义3个信号量,full标识缓冲区是否为满,avail标识缓冲区 是否为空.*/
intfd;
voidpthread1(void*arg); voidpthread2(void*arg); voidconsumer(void*arg); voidproductor(void*arg); intmain(intargc,char*argv[])
{
pthread_tid1,id2;
pthread_tmon_th_id; intret;
end_time=time(NULL)+30;
if((mkfifo(FIFO,O_CREAT|O_EXCL)<0)&&(errno!=EEXIST)) printf(\cannotcreatefifoserver\\n\); printf(\reparingfor readingbytes...\\n\); memset(buf_r,0,sizeof(buf_r)); fd=open(FIFO,O_RDWR|O_NONBLOCK,0); if(fd==-1) {
perror(\open\); exit(1); } ret=sem_init(&mutex,0,1); ret=sem_init(&avail,0,N); ret=sem_init(&full,0,0); if(ret!=0) {
perror(\sem_init\); }
ret=pthread_create(&id1,NULL,(void*)productor,NULL); if(ret!=0)
perror(\ret=pthread_create(&id2,NULL,(void*)consumer,NULL); if(ret!=0)
perror(\pthread_join(id1,NULL); pthread_join(id2,NULL); exit(0);
}
voidproductor(void*arg) {
inti,nwrite;
while(time(NULL) if(errno==EAGAIN) printf(\FIFOhasnotbeenreadyet.Pleasetrylater\\n\); } else printf(\FIFO\\n\); sem_post(&full); sem_post(&mutex); sleep(1); } } voidconsumer(void*arg) { intnolock=0; intret,nread; while(time(NULL) if(errno==EAGAIN) printf(\et\\n\); } printf(\read%sfromFIFO\\n\,buf_r); sem_post(&avail); sem_post(&mutex); sleep(1); } }
相关推荐: