读写锁

读写锁有三种状态:读锁、写锁和不锁
其特性为:读共享,写独占,写锁优先级高

// 初始化读写锁
int pthread_rwlock_init ( pthread_rwlock_t * restrict rwlock , 
                          const pthread_rwlockattr_t * restrict attr ) ;
// 销毁读写锁
int pthread_rwlock_destroy (pthread_rwlock_t * rwlock ) ;
// 加读锁
int pthread_rwlock_rdlock ( pthread_rwlock_t  * rwlock ) ;
// 加写锁
int pthread_rwlock_wrlock ( pthread_rwlock_t * rwlock ) ;
// 解锁
int pthread_rwlock_unlock ( pthread_rwlock_t * rwlock ) ;
// 尝试加读锁
int pthread_rwlock_tryrdlock ( pthread_rwlock_t * rwlock ) ;
// 尝试加写锁
int pthread_rwlock_trywrlock ( pthread_rwlock_t * rwlock ) ;

下面通过读写锁实现读者写者模型,有3个写者,5个读者:

  1 #include<stdio.h>
  2 #include<unistd.h>
  3 #include<pthread.h>
  4 int cont;
  5 pthread_rwlock_t rwlock;
  6 void *th_write(void *arg)
  7 {   
  8     int t;
  9     long int i = (long int)arg;
 10     
 11     while(1)
 12     {   
 13         usleep(1000);
 14         
 15         pthread_rwlock_wrlock(&rwlock);//加写锁
 16         t = cont;
 17         printf("=====write %ld: %lu: cont = %d, ++cont = %d\n",i,pthread_self(), t, ++cont);
 18         pthread_rwlock_unlock(&rwlock);//解锁
 19         
 20         usleep(1000);
 21     }
 22 }
 23 void *th_read(void *arg)
 24 {
 25     long int i = (long int)arg;
 26 
 27     while(1)
 28     {
 29         pthread_rwlock_rdlock(&rwlock);//加读锁
 30         printf("=======================read %ld: %lu: cont = %d\n",i,pthread_self(),cont);
 31         pthread_rwlock_unlock(&rwlock);//解锁
 32         usleep(900);
 33     }
 34 }
 35 int main(void)
 36 {
 37     long int i;
 38     pthread_t tid[8];
 39 
 40     pthread_rwlock_init(&rwlock,NULL);//初始化锁
 41     for(i = 0;i < 3;i++)
 42     {
 43         pthread_create(&tid[i],NULL,th_write,(void*)i);
 44     }
 45     for(i = 0;i < 5;i++)
 46     {
 47         pthread_create(&tid[i+3],NULL,th_read,(void*)i);
 48     }
 49     for(int i=0;i < 8;i++)
 50     {
 51         pthread_join(tid[i],NULL);
 52     }
 53     pthread_rwlock_destroy(&rwlock);//释放锁
 54 }

截取部分运行结果:
在这里插入图片描述

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值