Implementing ReaderWriterLock for seamless Read and Write Operations


In this article I will explain about how to implementing ReaderWriterLock for seamless Read and Write Operations

In a multi-threaded environment, suppose an object is shared by multiple read and a single write requests, to avoid concurrency problems (dead-lock situations), ReaderWriterLock class is used. It has AcquireReaderLock and ReleaseReaderLock methods to make a read request on a shared object. Similarly, for write operations we can use the AcquireWriterLock and ReleaseWriterLock methods.

The following code shows how to use a list object shared by both read and write operations performed on separate threads. When the write thread adds a random integer item to the list, read thread is not stopped or waited. Instead, it continues to read the values from the list. Just by obtaining the lock and releasing the lock during the read write operations enable the seamless output from both the threads.



static ReaderWriterLock rw = new ReaderWriterLock();
static List items = new List();

static void Main(string[] args)
{
new Thread(delegate() { while (items.Count <= 100) AppendItem(); }).Start();
new Thread(delegate() { while (items.Count <= 100) WriteTotal(); }).Start();
new Thread(delegate() { while (items.Count <= 100) WriteTotal(); }).Start();
}

static void WriteTotal()
{
rw.AcquireReaderLock(10000);
int tot = 0; foreach (int i in items) tot += i;
Console.WriteLine(tot);
rw.ReleaseReaderLock();
}

static void AppendItem()
{
rw.AcquireWriterLock(10000);
items.Add((new Random()).Next(10));
Thread.Sleep(500);
rw.ReleaseWriterLock();
}


Comments

No responses found. Be the first to comment...


  • Do not include your name, "with regards" etc in the comment. Write detailed comment, relevant to the topic.
  • No HTML formatting and links to other web sites are allowed.
  • This is a strictly moderated site. Absolutely no spam allowed.
  • Name:
    Email: