top button
Flag Notify
    Connect to us
      Site Registration

Site Registration

How to implement a read-write lock in C++ ?

+8 votes
849 views

Write a thread safe data structure such that there could be only one writer at a time but there could be n readers reading the data. You can consider that incrementing or decrementing a variable is an atomic operation. If more than one threads try to write simultaneously then just select one randomly and let others wait.

posted Feb 11, 2014 by Kanika Prashar

Share this question
Facebook Share Button Twitter Share Button LinkedIn Share Button

1 Answer

0 votes

Class ReadWriteLock
{
private int Read;
private int Write;
private static Object _S= new Object();
public void ReadWriteLock()
{
Write=0;
Read=0;
}
public void GetReadLock()
{
while(Write);
Interlocked.Increment(ref Read);
}

public void ReleaseReadLock()
{

 Interlocked.Decrement(ref Read);

}

public void GetWriteLock()
{
while(Read);
if(Read==0)
{
lock(_S)
{
if(Read==0)
{
Interlocked.Increment(ref Write);
}
}
}
}
}
public void ReleaseWriteLock()
{
Interlocked.Decrement(ref Write);
}

answer Feb 12, 2014 by Hiteshwar Thakur
Similar Questions
+4 votes

For ex : Given post order sequence 1 3 2 6 9 8 5
its pre order sequence is 5 2 1 3 8 6 9

+1 vote

JVM provides garbage collector. Can we do in C ? And what are the efficient ways to implement it in C lang ?

+2 votes

Please share the code or algorithm to delete a node from Threaded Binary Tree.

+4 votes

How to implement least recent use for the numbers displayed on phone screen ??

...