线程同步--------读写锁的使用

读写锁-------------指的是一个锁,而不是两个锁

特别重要12字:写独占,读共享; 写锁优先级高
主要应用函数:
(1)pthread_rwlock_init ------初始化
(2)pthread_rwlock_rdlock ----读锁
(3)pthread_rwlock_wrlock ----写锁
(4)pthread_rwlock_tryrdlock —try写锁
(5)pthread_rwlock_trywrlock —try读锁
(6)pthread_rwlock_unlock -------解锁
(7)pthread_rwlock_destory------毁锁
使用场景:读的次数远大于写的次数时;
**

代码分析

**

#include<stdlib.h>
#include<stdio.h>
#include<pthread.h>
#include<unistd.h>
pthread_rwlock_t rwlock;
int counter=0;//共享数据,写独占,读共享。

void *pthread_write(void * arg)
{
        int i= (int)arg;
        while(1)
        {       sleep(1);
                pthread_rwlock_wrlock(&rwlock);
                printf("-----write %dtn, counter = %d, tid=%lu\n",i,++counter,pthread_self());
                pthread_rwlock_unlock(&rwlock);
                sleep(3);
        }
}
void *pthread_read(void * arg)
{
        int i = (int)arg;
        while(1)
        {
                sleep(1);
                pthread_rwlock_rdlock(&rwlock);
                printf("-----read %dth, counter = %d,  tid=%lu\n",i,counter,pthread_self());
                pthread_rwlock_unlock(&rwlock);
                sleep(3);
        }
}
int main()
{
        pthread_rwlock_init(&rwlock,NULL);
        pthread_t tid[8];
        int i,ret;

        for(i=0;i<3;++i)
        {
                ret = pthread_create(&tid[i],NULL,pthread_write,(void*)i);
                if(ret != 0)
                        printf("pthread create error\n");
        }
        for(int i=0; i<5;i++)
        {
                ret = pthread_create(&tid[i+3],NULL,pthread_read,(void *)i);
                if(ret != 0)
                        printf("pthread_create error\n");
        }
        for(i=0;i<8;i++)
        {
                pthread_join(tid[i],NULL);
        }
        pthread_rwlock_unlock(&rwlock);
        return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

YanWenCheng_

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值