Board logo

标题: Linux多线程"生产者和消费者"实例(2) [打印本页]

作者: yuyang911220    时间: 2017-6-11 16:59     标题: Linux多线程"生产者和消费者"实例(2)

 /*创建两个线程*/
  /* 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);
  }
}





欢迎光临 电子技术论坛_中国专业的电子工程师学习交流社区-中电网技术论坛 (http://bbs.eccn.com/) Powered by Discuz! 7.0.0