我是靠谱客的博主 干净指甲油,这篇文章主要介绍【Linux】读写锁!!,现在分享给大家,希望可以做个参考。

读写锁的三二一模型

  • 三:三种关系 、读者与读者之间没有关系、写者和读者互斥且同步、写者与写者之间互斥
  • 二:两种对象、读者和写者
  • 一:一个交易场所
    读写锁应用的场景:在多线程程序里面,线程对临界资源的访问比较多,而对临界资源的修改较少。

在读写者模型里面,由于写操作的次数比较少。那么在该模型里面的写操作的优先级必读操作的优先级高。加入读的优先级比写优先级高,那么就会出现读操作在一直读,写操作就会出现饥饿现象。


读写锁
类型:pthread_rwlock_t

初始化和销毁读写锁

复制代码
1
2
3
4
#include <pthread.h> int pthread_rwlock_destroy(pthread_rwlock_t *rwlock); int pthread_rwlock_init(pthread_rwlock_t *restrict rwlock, const pthread_rwlockattr_t *restrict attr);

读写锁的加锁和解锁

复制代码
1
2
int pthread_rwlock_rdlock(pthread_rwlock_t *rwlock); int pthread_rwlock_tryrdlock(pthread_rwlock_t *rwlock);

实例:

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
#include<stdio.h> #include<pthread.h> #include<unistd.h> pthread_rwlock_t lock; int count = 0; void* route_read(void* arg){ int id = (int)arg; int t = count; while(1){ usleep(100000); pthread_rwlock_rdlock(&lock); printf("tid = %x id = %d t = %d count = %dn",pthread_self(),id,t,count); pthread_rwlock_unlock(&lock); sleep(1); } } void* route_write(void* arg){ int id = (int)arg; int t = count; while(1){ usleep(100000); pthread_rwlock_wrlock(&lock); printf("tid = %x id = %d t = %d ++count = %dn",pthread_self(),id,t,++count); pthread_rwlock_unlock(&lock); sleep(1); } } int main(){ pthread_t id[8]; int i = 0; pthread_rwlock_init(&lock,NULL); for(;i<3;i++){ pthread_create(&id[i],NULL,route_write,(void*)i); } for(i=3;i<8;i++){ pthread_create(&id[i],NULL,route_read,(void*)i); } for(i=0;i<8;i++) pthread_join(id[i],NULL); return 0; }

最后

以上就是干净指甲油最近收集整理的关于【Linux】读写锁!!的全部内容,更多相关【Linux】读写锁内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(47)

评论列表共有 0 条评论

立即
投稿
返回
顶部