仅使用互斥锁实现读写锁

清楚认识到读写锁分为共享锁(读锁)和独占锁(写锁),可能通过设置标志位记录读锁调用的次数结合互斥锁实现共享锁。但需要注意的是,以下的实现在多个写锁被阻塞时非常消耗计算机资源。因为线程阻塞在写锁中而没有被投入睡眠,导致轮询策略。避免轮询可通过互斥锁+条件变量实现读写锁,具体实现见上一篇博文。
以下是代码实现:

#include<pthread.h>
 
pthread_mutex_t rdLock = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_t wrLock = PTHREAD_MUTEX_INITIALIZER;
int readCnt = 0;//设置读锁调用次数的标志位
 
//实现读锁(共享锁)
void rdLock() {
	pthread_mutex_lock(&rdLock);
	readCnt++;
	if (readCnt == 1)//有人读,于是阻塞写锁
		pthread_mutex_lock(&wrLock);
	pthread_mutex_unlock(&rdLock);
}
 
void rdUnlock() {
	pthread_mutex_lock(&rdLock);
	readCnt--;
	if (readCnt == 0)//表示已没有人在读,释放写锁,可以写入了
		pthread_mutex_unlock(&wrLock);
	pthread_mutex_unlock(&rdLock);
}
 
void wrLock() {
	pthread_mutex_lock(&wrLcok);
}
 
void wrUnlock() {
	pthread_mutex_unlock(&wrLock);
}
posted @ 2021-08-25 15:59  wsl-hitsz  阅读(209)  评论(0编辑  收藏  举报