linux下简单封装读写锁
#ifndef CLEESRWLOCKER_INCLUDED #define CLEESRWLOCKER_INCLUDED #include <pthread.h> #include <unistd.h> #include <iostream> using namespace std; class CLeesRWLocker { public: CLeesRWLocker() { pthread_rwlock_init(&m_locker,NULL); m_bAbort=false; m_nReadCounter=0; m_nWriteCounter=0; cout<<"pthread_rwlock_init"<<endl; } ~CLeesRWLocker() { m_bAbort=true; while(m_nReadCounter||m_nWriteCounter) usleep(1); pthread_rwlock_destroy(&m_locker); cout<<"pthread_rwlock_init"<<endl; } bool ReadLock() { while(m_bAbort==false) { if(pthread_rwlock_tryrdlock(&m_locker)==0) { m_nReadCounter++; //cout<<"ReadLock OK"<<endl; return true; } usleep(0); } cout<<"ReadLock Failed"<<endl; return false; } bool WriteLock() { while(m_bAbort==false) { if(pthread_rwlock_trywrlock(&m_locker)==0) { m_nWriteCounter++; //cout<<"WriteLock OK"<<endl; return true; } usleep(0); } cout<<"WriteLock Failed"<<endl; return false; } bool TryReadLock(uint32_t nMillSeconds) { for(uint32_t i=0;i<nMillSeconds&&m_bAbort==false;i++) { if(pthread_rwlock_tryrdlock(&m_locker)==0) { m_nReadCounter++; cout<<"TryReadLock OK"<<endl; return true; } usleep(999); } cout<<"TryReadLock Failed"<<endl; return false; } bool TryWriteLock(uint32_t nMillSeconds) { for(uint32_t i=0;i<nMillSeconds&&m_bAbort==false;i++) { if(pthread_rwlock_trywrlock(&m_locker)==0) { m_nWriteCounter++; cout<<"TryWriteLock OK"<<endl; return true; } usleep(999); } cout<<"TryWriteLock Failed"<<endl; return false; } bool UnLock() { if(m_nWriteCounter>0) m_nWriteCounter=0; if(m_nReadCounter>0) m_nReadCounter--; //cout<<"UnLock m_nWriteCounter="<<m_nWriteCounter<<" m_nReadCounter="<<m_nReadCounter<<endl; pthread_rwlock_unlock(&m_locker); } //终止所有读写锁 void Abort() { m_bAbort=true; } private: bool m_bAbort; pthread_rwlock_t m_locker; uint32_t m_nReadCounter; uint32_t m_nWriteCounter; }; #endif // CLEESRWLOCKER_INCLUDED