C 优先读者 读者/写者问题

#include <stdio.h> 
#include <stdlib.h>  
#include <pthread.h>  


  
#define N_WRITER 2 //写者数目  
#define N_READER 5 //读者数目  
#define W_SLEEP  1 //控制写频率  
#define R_SLEEP  1 //控制读频率  
  
  
pthread_t wid[N_WRITER],rid[N_READER];  
pthread_mutex_t writeLock = PTHREAD_MUTEX_INITIALIZER;//同一时间只能一个人写文件,互斥  
pthread_mutex_t accessReaderCnt = PTHREAD_MUTEX_INITIALIZER;//同一时间只能有一个人访问 readerCnt  
int readerid = 0;
int writerid = 0;
int data = 0;  
int readerCnt = 0;  
void write(int id)  
{  
 
    int rd = rand()%100;  
    printf("writer %d write %d\n",id,rd);  
    data = rd;  
}  
void read(int id)  
{  
    printf("reader %d read %d\n",id,data);  
}  
void * writer(void * in)  
{  
int id;
id = ++writerid;
    while(1)  
    {  
        pthread_mutex_lock(&writeLock);  
        write(id);  
        pthread_mutex_unlock(&writeLock);  
        sleep(W_SLEEP);  
    }  
    pthread_exit((void *) 0);  
}  
  
void * reader (void * in)  
{  
int id;
id = ++readerid;
    while(1)  
    {  
        pthread_mutex_lock(&accessReaderCnt);  
        readerCnt++;  
        if(readerCnt == 1)
{  
            pthread_mutex_lock(&writeLock);  
        }  
        pthread_mutex_unlock(&accessReaderCnt);  
          
        read(id);  
          
        pthread_mutex_lock(&accessReaderCnt);  
        readerCnt--;  
        if(readerCnt == 0)
{  
            pthread_mutex_unlock(&writeLock);  
        }  
        pthread_mutex_unlock(&accessReaderCnt);  
        sleep(R_SLEEP);  
    }  
    pthread_exit((void *) 0);  
}  
  
int main()  
{  
    int i = 0;  
    for(i = 0; i < N_READER; i++)  
    {  
        pthread_create(&wid[i],NULL,reader,NULL);  
    }  
    for(i = 0; i < N_WRITER; i++)  
    {  
        pthread_create(&rid[i],NULL,writer,NULL);  
}  
    while(1)
{  
        sleep(10);  
    }  
    return 0;  
}  
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值