读者写者模型

读者写者模型

读者与写者之间的关系:
读者与读者:无关系
写者与写者:互斥
读者与写者:互斥

注:写独占,读共享,写锁优先级高。

读写锁接口:

//1.初始化
int pthread_rwlock_init(pthread_rwlock_t *restrict rwlock,const pthread_rwlockattr_t *restrict attr);

//2.销毁
int pthread_rwlock_destory(pthread_rwlock_t *rwlock);

//3.加锁和解锁
int pthread_rwlock_rdlock(pthread_rwlock_t * rwlock);    //读加锁
int pthread_rwlock_wrlock(pthread_rwlock_t * rwlock);    //写加锁

int pthread_rwlock_unlock(pthread_rwlock_t * rwlock);
#include<stdio.h>
#include<unistd.h>
#include<pthread.h>
#include<stdlib.h>

int counter;
pthread_rwlock_t rwlock;

void* _read(void* arg)
{
    int t;
    int i=*(int*)arg;
    free(arg);

    while(1)
    {
        pthread_rwlock_rdlock(&rwlock);
        printf("read: %d :%#x :counter=%d\n",i,pthread_self(),counter);
        pthread_rwlock_unlock(&rwlock);
        sleep(1);
    }

}

void* _write(void* arg)
{
    int t;
    int i=*(int*)arg;
    free(arg);

    while(1)
    {
        t=counter;
        usleep(1000);

        pthread_rwlock_wrlock(&rwlock);
        printf("write:%d :%#x :counter=%d ++counter=%d\n",i,pthread_self(),t,++counter);
        pthread_rwlock_unlock(&rwlock);
        sleep(2);
    }
}

int main()
{
    int i;
    pthread_t tid[8];

    pthread_rwlock_init(&rwlock,NULL);

    for(i=0;i<3;i++)
    {
        int*p=(int*)malloc(sizeof(int));
        *p=i;
        pthread_create(&tid[i],NULL,_write,(void*)p);
    }

    for(i=0;i<5;i++)
    {
        int* p=(int*)malloc(sizeof(int));
        *p=i;
        pthread_create(&tid[i+3],NULL,_read,(void*)p);
    }

    for(i=0;i<8;i++)
    {
        pthread_join(tid[i],NULL);
    }

    pthread_rwlock_destroy(&rwlock);
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值