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

来源:互联网 发布:mac魅可三里屯店铺电话 编辑:程序博客网 时间:2024/06/05 23:51
#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 lockbool _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

原创粉丝点击