基于互斥锁和条件变量实现读写锁,写优先

#include <stdio.h>
#include <pthread.h>
#include <unistd.h>
#include <stdlib.h>
class MyRWLock
{
	public:
		MyRWLock():_stat(0),_have_wlock_wait(false){
			pthread_mutex_init(&_mutex,NULL);
			pthread_cond_init(&_cond,NULL);
		}
		
		~MyRWLock() {
			pthread_mutex_destroy(&_mutex);
			pthread_cond_destroy(&_cond);
		}
		void ReadLock() {
			pthread_mutex_lock(&_mutex);
			while (_stat < 0 || _have_wlock_wait) {
				pthread_cond_wait(&_cond,&_mutex);
			}
			++_stat;
			pthread_mutex_unlock(&_mutex);
		}

		void ReadUnlock() {
			pthread_mutex_lock(&_mutex);
			if (--_stat == 0) {
				pthread_cond_signal(&_cond);
			}
			pthread_mutex_unlock(&_mutex);
		}

		void WriteLock() {
			pthread_mutex_lock(&_mutex);
			while (_stat != 0) {
				_have_wlock_wait = true;
				pthread_cond_wait(&_cond,&_mutex);
			}
			_stat = -1;
			_have_wlock_wait= false;
			pthread_mutex_unlock(&_mutex);
		}

		void WriteUnlock() {
			pthread_mutex_lock(&_mutex);
			_stat = 0;
			pthread_cond_broadcast(&_cond);
			pthread_mutex_unlock(&_mutex);
		}
	private:
		pthread_mutex_t _mutex;
		pthread_cond_t _cond;
		int _stat; // == 0 not lock ,> 0 read lock count,< 0 have write lock
		bool _have_wlock_wait;
};
class MyRLockWrapper {
	public:
		MyRLockWrapper(MyRWLock &lock):_lock(lock) {
			_lock.ReadLock();
		}
		virtual ~MyRLockWrapper() {
			_lock.ReadUnlock();
		}
	private:
		MyRLockWrapper();
		MyRLockWrapper(const MyRLockWrapper& orig);
		MyRLockWrapper& operator=(const MyRLockWrapper &orig);
		MyRWLock &_lock;
};
class MyWLockWrapper {
	public:
		MyWLockWrapper(MyRWLock &lock):_lock(lock) {
			_lock.WriteLock();
		}
		virtual ~MyWLockWrapper() {
			_lock.WriteUnlock();
		}
	private:
		MyWLockWrapper();
		MyWLockWrapper(const MyWLockWrapper& orig);
		MyWLockWrapper& operator=(const MyWLockWrapper &orig);
		MyRWLock &_lock;
};

MyRWLock g_lock;

void * rfunc(void*args) {
	while(1) {
		{
			MyRLockWrapper lock(g_lock);
			printf("at rfunc,[%lu]\n",pthread_self());
			sleep(1);
		}
	}
}
void * wfunc(void*args) {
	while(1) {
		{
			MyWLockWrapper lock(g_lock);
			printf("at wfunc,[%lu]\n",pthread_self());
			sleep(1);
		}
	}
}

int main(void) {
	pthread_t rtid[1],wtid[1];

	for(int i =0;i<1;i++){
		pthread_create(&rtid[i],NULL,rfunc,NULL);
	}
	for(int i =0;i<1;i++){
		pthread_create(&wtid[i],NULL,wfunc,NULL);
	}
	pause();
	return 0;
}
 


备注:本篇并非完全意义上的原创,是参考了如下文章的思路,进行了实现,并增加了写优先的策略,在此谨向作者致敬

http://blog.csdn.net/raomeng1/article/details/7685421

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值