#ifndef _SV_READ_WRITE_LOCK_H_ #define _SV_READ_WRITE_LOCK_H_ #include "usg_common.h" #include "svsem.h" class SvReadWriteLock { private: unsigned int readCount = 0; int countMutex; int writeMutex; public: SvReadWriteLock() { countMutex = svsem_get(IPC_PRIVATE, 1); writeMutex = svsem_get(IPC_PRIVATE, 1); } void lockRead() { //readCount是共享变量,所以需要实现一个锁来控制读写 //synchronized(ReadWriteLock.class){} svsem_wait(&countMutex); //只有是第一个读者,才将写锁加锁。其他的读者都是进行下一步 if(readCount == 0){ svsem_wait(&writeMutex); } ++readCount; svsem_post(&countMutex); } void unlockRead(){ svsem_wait(&countMutex); readCount--; //只有当读者都读完了,才会进行写操作 if(readCount == 0){ svsem_post(&writeMutex); } svsem_post(&countMutex); } void lockWrite(){ svsem_wait(&writeMutex); } void unlockWrite(){ svsem_post(&writeMutex); } }; #endif