- UID
- 1029342
- 性别
- 男
|
/*创建两个线程*/
/* ret = pthread_create(&id2,NULL,(void *)consumer,NULL);
if(ret !=0)
perror("pthread create 2\n");*/
printf("mid pthread\n");
ret = pthread_create(&id1,NULL,(void *)productor,NULL);
if(ret!=0)
perror("pthread create 1\n");
ret = pthread_create(&id2,NULL,(void *)consumer,NULL);
if(ret !=0)
perror("pthread create 2\n");
pthread_join(id1,NULL);
pthread_join(id2,NULL);
exit(0);
}
/*生产者线程*/
void productor(void *arg)
{
int i,nwrite;
while(time(NULL)<end_time)
{
/* P 操作信号量avail和mutex*/
sem_wait(&avail);
sem_wait(&mutex);
/*生产者写入数据*/
if((nwrite=write(fd,"hello",5))==-1)
{
if(errno==EAGAIN)
printf("The FIFO has not been read yet.Please try later\n");
}
else
printf("write hello to the FIFO\n");
/*V操作信号量full和mutex*/
sem_post(&full);
sem_post(&mutex);
sleep(1);
}
}
/*消费者线程*/
void consumer(void *arg)
{
int nolock = 0;
int ret,nread;
while(time(NULL)<end_time)
{
/*P操作信号量full和mutex*/
sem_wait(&full);
sem_wait(&mutex);
memset(buf_r,0,sizeof(buf_r));
if((nread=read(fd,buf_r,100))==1)
{
if(errno==EAGAIN)
printf("no data yet\n");
}
printf("read %s from FIFO\n",buf_r);
sem_post(&avail);
sem_post(&mutex);
sleep(1);
}
}
|
|