Chinaunix首页 | 论坛 | 博客
  • 博客访问: 450647
  • 博文数量: 60
  • 博客积分: 1039
  • 博客等级: 准尉
  • 技术积分: 939
  • 用 户 组: 普通用户
  • 注册时间: 2012-03-01 09:24
个人简介

你是我的我是大家的!

文章分类
文章存档

2013年(1)

2012年(59)

分类: LINUX

2012-10-28 21:44:23

#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;
}
阅读(3801) | 评论(0) | 转发(1) |
给主人留下些什么吧!~~