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()
int tot = 0; foreach (int i in items) tot += i;

static void AppendItem()
items.Add((new Random()).Next(10));


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: