Chinaunix首页 | 论坛 | 博客
  • 博客访问: 1501218
  • 博文数量: 329
  • 博客积分: 2773
  • 博客等级: 少校
  • 技术积分: 4219
  • 用 户 组: 普通用户
  • 注册时间: 2012-02-24 14:17
个人简介

淡定从容,宁静致远

文章分类

全部博文(329)

文章存档

2016年(4)

2015年(50)

2014年(68)

2013年(45)

2012年(162)

分类: LINUX

2012-10-25 09:51:50

 #include "stdio.h"
 #include
 #include


 #define N_WRITER 3            //写者数目
 #define N_READER 5            //读者数目
 #define W_SLEEP  1            //控制写频率
 #define R_SLEEP  1            //控制读频率

 pthread_t exitA;
 pthread_t wid[N_WRITER],rid[N_READER];
 const int MAX_RAND = 1000;    //产生的最大随机数
 pthread_mutex_t writeLock = PTHREAD_MUTEX_INITIALIZER;        //同一时间只能一个人写文件,互斥
 pthread_mutex_t accessReaderCnt = PTHREAD_MUTEX_INITIALIZER;  //同一时间只能有一个人访问 readerCnt
 int data = 0;
 int readerCnt = 0;
//*********************写操作函数*******************************************************************
 void write()
 {
     int rd = rand()%100;//产生一百以内的随机数随机数
     printf("write %d\n",rd);//打印随机数
     data = rd;//把随机数赋值给data
 }
//********************读操作函数*******************************************************************
 void read()
 {
     printf("read %d\n",data);//打印随机数
 }
//*********************写者处理函数******************************************************************
 void * writer(void * in)
 {
     while(1)
     {//保证一个人写操作
         pthread_mutex_lock(&writeLock);
         write();
         pthread_mutex_unlock(&writeLock);
         sleep(W_SLEEP);//调整频率
     }
     pthread_exit((void *) 0);//退出线程
 }
//**************读者处理函数*******************************************************************
 void * reader (void * in)
 {
     while(1)
     {
         pthread_mutex_lock(&accessReaderCnt);//读的时候枷锁
         readerCnt++;//读者数目加一
         if(readerCnt == 1){//当读者数目为一
             pthread_mutex_lock(&writeLock);
         }
         pthread_mutex_unlock(&accessReaderCnt);//有读请求的解锁

         read();//读函数

         pthread_mutex_lock(&accessReaderCnt);//对所有读请求者上锁
         readerCnt--;
         if(readerCnt == 0){
             pthread_mutex_unlock(&writeLock);//当没有读者的时候,允许写者进行操作
         }
         pthread_mutex_unlock(&accessReaderCnt);//解锁
         sleep(R_SLEEP);//调整频率
     }
     pthread_exit((void *) 0);//退出线程
 }
//***************退出函数************************************************************************
void* exit_Q()
{
    int c;
    for(;;){
        c=getchar();    
        if(c == 'q' || c == 'Q'){
            exit(10);
            break;
        }
    }
        
}
 int main()
 {
     int i = 0;
    printf("快速按q或Q和enter退出");
     for(i = 0; i < N_READER; i++)//读者的数目
     {
         pthread_create(&rid[i],NULL,reader,NULL);//创建读者线程
     }
     for(i = 0; i < N_WRITER; i++)//写者的数目
     {
         pthread_create(&wid[i],NULL,writer,NULL);//创建写者线程
     }
    pthread_create(&exitA,NULL,exit_Q,NULL);
     while(1){
         sleep(10);
     }
     return 0;
 }
阅读(602) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~