利用条件信号量设计读写锁
1 一个资源同时可以有多个读写,但是只能有一个写锁
2 用flag代表锁的状态,
#define un_lock 0
#define r_lock 1 //上一把读锁加一个r_lock
#define w_lock -1
伪代码
1 LOCK_R
pthread_lock(resource.mutex)
while(resource.flag < 0 ) //说明当前资源为写锁
pthread_cond_wait(resource.cond, resource.mutex)
//说明当前资源为无锁或者读锁,再加一把读锁
resource.flag+=r_lock
pthread_unlock(resource.mutex)
2 UNLOCK_R
pthread_lock(resource.mutex)
//减去一把读锁
resource.flag-=r_lock
if (resource.flag == 0) //说明当前资源为写锁
pthread_cond_broadcast(resource.cond) //这个操作激活所有上写锁的线程
pthread_unlock(resource.mutex)
3 LOCK_W
pthread_lock(resource.mutex)
while(resource.flag != 0 ) //说明当前资源为写锁或者读锁
pthread_cond_wait(resource.cond, resource.mutex)
//说明当前资源为无锁
resource.flag=w_lock
pthread_unlock(resource.mutex)
4 UNLOCK_W
pthread_lock(resource.mutex)
//减去写锁
resource.flag=w_lock
pthread_cond_broadcast(resource.cond) //这个操作激活所有上写锁和读锁的线程