Google Interview Question
Software Engineer / Developers/**
*
* <p>Title: ReadWriteLock</p>
* <p>Description: ReadWriteLock using Mutex</p>
* @author shaohui.liu
* @date Apr 13, 2011
*/
public class ReadWriteLock
{
interface Mutex
{
void lock();
void unlock();
}
private int readerCounter = 0;
private Mutex counterMutex;
private Mutex readerWriteMutex;
public void read_lock()
{
counterMutex.lock();
if (readerCounter == 0)
{
readerCounter++;
readerWriteMutex.lock();
}
else
{
readerCounter++;
}
counterMutex.unlock();
}
public void read_unlock()
{
counterMutex.lock();
readerCounter--;
if (readerCounter == 0)
{
readerWriteMutex.unlock();
}
counterMutex.unlock();
}
public void write_lock()
{
readerWriteMutex.lock();
}
public void write_unlock()
{
readerWriteMutex.unlock();
}
}
hi can u explain why u have used two mutex obj..e.g
private Mutex counterMutex;
private Mutex readerWriteMutex;
also plz explain the algo..??
Agree with the comment that the code won't work. The problem is only the thread that locks the mutex can unlock it.
The code has one problem
First reader executes read_lock(). He locks readerWriter. readerCounter = 1
Second reader executes read_lock(). readerCounter = 2
First reader executes read_unlock(). Here it does no release readerWriterLock, since readerCount = 1.
Second reader executes read_unlock. Will try to release readerWriter lock since readerCount=0, but will not be able to release lock , since it did not lock it.
think of the algorithm with some considerations in mind:
1. if you read, you want to prevent some process writing to it as you do
2. multiple process may read
3. when you write, same thing as 1 and 2
so the counter is to count how many processes are read/writing. Before changing the counter we lock the counter so other processes cannot change it.
the counter keeps track of how many read/write are currently in progress and the lock needs to wait for before totally unlocking
that should help you understand this code. gj btw.
- mytestaccount2 August 17, 2013