1.读写锁的相关介绍
- 当有一个线程已经持有互斥锁时,互斥锁将所有试图进入临界区的线程都阻塞住。但是考虑一种情形,当前持有互斥锁的线程只是要读访问共享资源,而同时有其它几个线程也想读取这个共享资源,但是由于互斥锁的排它性,所有其它线程都无法获取锁,也就无法读访问共享资源了,但是实际上多个线程同时读访问共享资源并不会导致问题。
- 在对数据的读写操作中,更多的是读操作,写操作较少,例如对数据库数据的读写应用。为了满足当前能够允许多个读出,但只允许一个写入的需求,线程提供了读写锁来实现。
- 读写锁的特点:
- 如果有其它线程读数据,则允许其它线程执行读操作,但不允许写操作。
- 如果有其它线程写数据,则其它线程都不允许读、写操作。
- 写是独占的,写的优先级高
2.读写锁相关操作函数
- 读写锁的类型
pthread_rwlock_t
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_tryrdlock(pthread_rwlock_t *rwlock);
int pthread_rwlock_wrlock(pthread_rwlock_t *rwlock);
int pthread_rwlock_trywrlock(pthread_rwlock_t *rwlock);
int pthread_rwlock_unlock(pthread_rwlock_t *rwlock);
3.读写锁代码举例
#include <string.h>
#include <pthread.h>
#include <unistd.h>
#include <stdlib.h>
#include <iostream>
using namespace std;
int num = 1;
pthread_rwlock_t rwlock;
void * write(void * arg)
{
while (1)
{
pthread_rwlock_wrlock(&rwlock);
num ++ ;
printf("+++write tid: %ld, num: %d\n", pthread_self(), num);
pthread_rwlock_unlock(&rwlock);
usleep(100);
}
pthread_exit(NULL);
}
void * read(void * arg)
{
while (1)
{
pthread_rwlock_rdlock(&rwlock);
printf("===read tid: %ld, num: %d\n", pthread_self(), num);
pthread_rwlock_unlock(&rwlock);
usleep(100);
}
pthread_exit(NULL);
}
int main()
{
pthread_rwlock_init(&rwlock, NULL);
pthread_t wtid[3], rtid[5];
for (int i = 0; i < 3; i ++ )
{
pthread_create(&wtid[i], NULL, write, NULL);
}
for (int i = 0; i < 5; i ++ )
{
pthread_create(&rtid[i], NULL, read, NULL);
}
for (int i = 0; i < 3; i ++ )
{
pthread_detach(wtid[i]);
}
for (int i = 0; i < 5; i ++ )
{
pthread_detach(rtid[i]);
}
pthread_rwlock_destroy(&rwlock);
pthread_exit(NULL);
return 0;
}
4.man文档中无法查看相关函数怎么办
- 先输入命令
sudo apt-get update
错误:1 https:
无法解析域名“mirrors.tuna.tsinghua.edu.cn”
错误:2 https:
无法解析域名“mirrors.tuna.tsinghua.edu.cn”
错误:3 https:
无法解析域名“mirrors.tuna.tsinghua.edu.cn”
错误:4 https:
无法解析域名“mirrors.tuna.tsinghua.edu.cn”
错误:5 https:
无法解析域名“mirrors.tuna.tsinghua.edu.cn”
正在读取软件包列表... 完成
正在分析软件包的依赖关系树
正在读取状态信息... 完成
所有软件包均为最新。
W: 无法下载 https:
W: 无法下载 https:
W: 无法下载 https:
W: 无法下载 https:
W: 无法下载 https:
W: 部分索引文件下载失败。如果忽略它们,那将转而使用旧的索引文件。
1. sudo vim /etc/resolv.conf # 添加如下内容
nameserver 8.8.8.8
nameserver 127.0.0.1
options edns0
2. 输入Esc,:wq,保存并退出
3. sudo /etc/init.d/networking restart
- 解决以上问题之后输入命令
sudo apt-get install manpages-posix-dev
即可。