ReadWriteLock
给一个Mutex,里面有lock(),unlock()
实现一个ReadWriteLock, PRAM CREW (同步读, 读时lock写, 写时lock写). 需要实现的方法有, readLock(), readUnlock(), writeLock(), writeUnlock()
这个没什么好讲的…基础os操作… 这题好像软软经常出, 所以我就做一下, 保佑onsite面试成功.
public class ReadWriteLock { interface Mutex {// given an mutex public void lock(); public void unlock(); } Mutex readLock; // read lock, in order to support PRAM CREW. it only lock when Mutex writeLock; // write lock. only lock when read perform. int numsOfreadLock = 0; public void readlock() { readLock.lock(); numsOfreadLock++; if (numsOfreadLock == 1) writeLock.lock(); readLock.unlock(); //concurrent read PRAM CREW } public void readunlock() { readLock.lock(); numsOfreadLock--; if (numsOfreadLock == 0) writeLock.unlock(); readLock.unlock(); //concurrent read PRAM CREW } public void writelock() { writeLock.lock(); } public void writeunlock() { writeLock.unlock(); } }
Leave A Comment