读写锁
最后更新于:2022-04-02 04:06:21
[TOC]
## 读写锁
- 读写锁是一种**特殊的自旋锁**
- 允许多个读者同时访问资源以提高读性能
- 对于写操作则是互斥的
提供的api
```
pthread_rwlock_t
pthread_rwlock_rdlock(读锁)
pthread_rwlock_wrlock(写锁)
```
#include
#include
#include
#include
pthread_rwlock_t rwlock = PTHREAD_RWLOCK_INITIALIZER;
int num =0;
void *reader(void*){
int times = 100000;
while(times--){
pthread_rwlock_rdlock(&rwlock);
if (times % 1000==0){
printf("print num in reader:num%d\n", num);
usleep(10);
}
pthread_rwlock_unlock(&rwlock)
}
}
void *writer(void*){
int times = 100000;
while(times--){
pthread_rwlock_wrlock(&rwlock);
num++;
pthread_rwlock_unlock(&rwlock);
}
}
int main(){
printf("stat in main function.");
pthread_t thread1,thread2,thread3;
pthread_create(&thread1,NULL,&reader,NULL);
pthread_create(&thread2,NULL,&reader,NULL);
pthread_create(&thread3,NULL,&writer,NULL);
pthread_join(thread1,NULL);
pthread_join(thread2,NULL);
printf("print in main function:num=%d",num);
return 0;
}
```
';