Library tutorials & articles

.NET Threading Part II

ReaderWriterLock

Another popular design pattern introduced as a class in the .NET framework is the ReaderWriterLock. This class allows an unlimited amount of read locks or one write lock, but not both. This allows anyone to read the protected resource, as long as nobody is writing to the protected resource and allows only one thread to write to the protected resource at any one time. Listing 1 presents a sample using the ReaderWriterLock class.

Listing 1: ReaderWriterLock Class

using System;
using System.Threading;

namespace ConsoleApplication9
{
    class Class1
    {
        public Class1()
        {
            rwlock = new ReaderWriterLock();
            val = "Writer Sequence Number is 1";
        }

        private ReaderWriterLock rwlock;
        private string val;

        public void Reader()
        {
            rwlock.AcquireReaderLock(Timeout.Infinite);
            Console.WriteLine("Acquired Read Handle: "
                + "Value = {0}", val);
            Thread.Sleep(1);
            Console.WriteLine("Releasing Read Handle");
            rwlock.ReleaseReaderLock();
        }

        public void Writer()
        {
            rwlock.AcquireWriterLock(Timeout.Infinite);
            Console.WriteLine("Acquired Write Handle");
            int id = rwlock.WriterSeqNum;
            Console.WriteLine("Writer Sequence Number "
                "is {0}", id);
            Thread.Sleep(1);
            val = "Writer ";
            Thread.Sleep(1);
            val += "Sequence ";
            Thread.Sleep(1);
            val += "Number ";
            Thread.Sleep(1);
            val += "is ";
            Thread.Sleep(1);
            val += id;
            Console.WriteLine("Releasing Write Handle");
            rwlock.ReleaseWriterLock();
        }

        static void Main(string[] args)
        {
            Class1 obj = new Class1();

            const int n = 1000;
            Thread[] reader = new Thread[n];
            Thread[] writer = new Thread[10];

            for (int i= 0; i< n; i++)
            {
                reader[i] = new Thread(
                    new ThreadStart(obj.Reader));
                if (i< 10)
                {
                    writer[i] = new Thread(
                        new ThreadStart(obj.Writer));
                };
            }

            for (int i= 0; i< n; i++)
            {
                reader[i].Start();
                if (i< 10)
                {
                    writer[i].Start();
                };
            }
        }
    }
}

In the above listing, I create 10 writer threads and 1000 reader threads. I parameterized the number of reader threads so that I could quickly trigger different behaviors in the code by modifying the number of reader threads. Once the threads are started they attempt to acquire read and write lock on the ReaderWriterLock object. If you run the code, then you can see the writer threads have a difficult time acquiring write locks. I tried to put as many small sleep statements as I could to force the threads to swap out of memory earlier than they would have normally.

Comments

  1. 10 Nov 2004 at 21:30
    Greetings-
    I have been doing alot of reading in this area and am frankly confused on which model/classes to use for a specific implementation I am working on. Perhaps you could shed some light.

    I have a large treeview on a UI thread, with nodes that contain collections of images that take a long time to render previews for in a panel. I would like to let a worker thread render the set of previews based on the treeview node selected, passing each preview back to the ui thread as they complete. Of course, it's bad form to have a worker thread access objects in the UI thread.

    I have tried async delegate calls and got it working on the UI thread, but it still locks the UI while it's rendering the previews. I am confused about wether to use events, a ThreadPool, Mutex stuff, or what?

    Can you help me out here?

    Many Thanks
  2. 12 Feb 2004 at 11:57

    hi, interesting article you've written here. just one question, and that is do you know of a function in .NET/C# equivalent to the old PostThreadMessage. The intention here is not to pass any information to a spawned thread via the LPARAM parameter, but rather just to inform the thread of the fact that some information is ready for them to collect (available at a singleton object which is made thread-safe). I tried using the approach of firing events and having the event handled by a delegate but only managed to make this work in the context of the same thread, not across threads. Any ideas?


    Thanks


    Alastair.

  3. 01 Jan 1999 at 00:00

    This thread is for discussions of .NET Threading Part II.

Leave a comment

Sign in or Join us (it's free).

Randy Charles Morin Randy's article are Copyright 1998-2003 Randy Charles Morin

Related podcasts

  • A Practical Look at Silverlight 2 Part 1

    Now that Silverlight 2 is at the Olympics and making a big splash, we wanted to explore this fascinating technology more. Microsoft Silverlight 2 is a cross-browser, cross-platform, and cross-device plug-in for delivering the next generation of .NET based media experiences and rich interactive ap...

Events coming up

  • Dec 9

    GL.net Group Meeting - December 2009

    Gloucester, United Kingdom

    The beginning of this year holiday season will belong to mocks. Ronnie and Stephen will take us for a tour around exciting world of unit testing.

Want to stay in touch with what's going on? Follow us on twitter!