Chinaunix首页 | 论坛 | 博客
  • 博客访问: 36480
  • 博文数量: 10
  • 博客积分: 112
  • 博客等级: 民兵
  • 技术积分: 56
  • 用 户 组: 普通用户
  • 注册时间: 2012-06-01 08:28
文章分类
文章存档

2012年(10)

最近访客

分类:

2012-11-05 17:08:49

原文地址:读者写者问题代码 作者:shy永久

#include
#include
#include
#include
sem_t w_sem, r_sem;
int read_count = 0;
void *reader(void *arg)
{
    //int read_count = 0;   //会造成死锁
    while(1) {
      sem_wait(&r_sem);
      if (read_count == 0) {
        sem_wait(&w_sem);       //有读者进入,不允许写文件
      }
      read_count++;
      printf("the number of reader is:%d\n", read_count);
      sem_post(&r_sem);
      printf("the reader is reading!\n");    //允许多个读者进行读
      sleep(1);
      sem_wait(&r_sem);
      read_count--;
      if (read_count == 0) {
        sem_post(&w_sem);
      }
      sem_post(&r_sem);
    }
    return (void*)0;
}
 
void *writer(void *arg)
{
    while(1) {
      sem_wait(&w_sem);       //不允许多个写者同时写文件
      printf("the writer is writing!\n");
      sleep(1);
      sem_post(&w_sem);
      sleep(3);
    }
    return (void*)0;
}
 
int main()
{
    pthread_t pid_reader, pid_reader2, pid_writer;
    sem_init(&w_sem, 0 , 1);
  sem_init(&r_sem, 0 , 1);
    pthread_create(&pid_writer, NULL, writer, NULL);
    pthread_create(&pid_reader, NULL, reader, NULL);
    pthread_create(&pid_reader2, NULL, reader, NULL);
    pthread_join(pid_reader, NULL);
    pthread_join(pid_reader2, NULL);
  pthread_join(pid_writer, NULL);
  sem_destroy(&w_sem);
  sem_destroy(&r_sem);
    return 0;
}
阅读(2105) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~