linux系统编程 读写锁

特点:与互斥锁类似,但读写锁允许更高的并行性。(写时独占,读时共享,写锁优先级高)

读写锁状态:

  • 读模式下加锁
  • 写模式下加锁
  • 不加锁
  1 /*头文件:#include<pthread.h>
  2 
  3 初始化读写锁:
  4 动态初始化:
  5 int pthread_rwlock_init(pthread_rwlock_t *restrict rwlock,const pthread_rwlockattr_t *restrict attr);
  6 静态初始化:
  7 pthread_rwlock_t rwlock = PTHREAD_RWLOCK_INITIALIZER;
  8 
  9 销毁锁:
 10 int pthread_rwlock_destroy(pthread_rwlock_t *rwlock);
 11 
 12 加读锁:
 13 int pthread_rwlock_rdlock(pthread_rwlock_t *rwlock);
 14 
 15 尝试加读锁:
 16 int pthread_rwlock_tryrdlock(pthread_rwlock_t *rwlock);
 17 
 18 加写锁:
 19 int pthread_rwlock_wrlock(pthread_rwlock_t *rwlock);
 20 
 21 尝试加写锁
 22 int pthread_rwlock_trywrlock(pthread_rwlock_t *rwlock);
 23 
 24 解锁:
 25 int pthread_rwlock_unlock(pthread_rwlock_t *rwlock)
 26 
 27 pthread_rwlock_t rwlock:定义rwlock为读写锁
 28 */
 29 
 30 #include<stdio.h>
 31 #include<pthread.h>
 32 #include<unistd.h>
 33 #include<stdlib.h>
 34 //定义全局变量:锁
 35 pthread_rwlock_t rwlock;
 36 
 37 int count=500;
 38 void *th1(void *)
 39 {
 40         while(1){
 41         //加锁
 42         pthread_rwlock_rdlock(&rwlock);
 43         printf("read_____%d\n",count);
 44         pthread_rwlock_unlock(&rwlock);
 45         sleep(0);
 46         }
47 }
 48 void *th2(void *)
 49 {
 50         while(1){
 51         //加锁
 52         int i;
 53         i=pthread_rwlock_wrlock(&rwlock);
 54         printf("write____%d\n",++count);
 55         pthread_rwlock_unlock(&rwlock);
 56         if(i!=0){printf("sdfsf\n");}
 57         sleep(0);
 58         }
 59 
 60 }
 61 void main(void)
 62 {
 63         //创建两个线程
 64         pthread_t TH1,TH2;
 65         pthread_create(&TH1,NULL,th1,NULL);
 66         pthread_create(&TH2,NULL,th2,NULL);
 67         //初始化互斥锁
 68         pthread_rwlock_init(&rwlock,NULL);
 69 
 70         while(1);
 71         //回收线程
 72         pthread_join(TH1,NULL);
 73         pthread_join(TH2,NULL);
 74 }

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值