-1

Learning about ReaderWriterLockSlim. Trying to understand why ReaderWriterLockSlim in better than any other lock like for example Monitor?

What is difference between EnterWriteLock() and EnterReadLock(). I suppose that EnterWriteLock() has more chances to get lock than EnterReadLock(). but I suppose I can use EnterReadLock() in places when I need just write - it only will be slower.

   class Program
    {

        static ReaderWriterLockSlim _rw = new ReaderWriterLockSlim();
        static List<int> _items = new List<int>();
        static Random _random = new Random();

        static void Main(string[] args)
        {
            new Thread(read).Start() ;
            new Thread(read).Start();
            new Thread(read).Start();

            new Thread(()=>write("A")).Start();
            new Thread(() => write("B")).Start();


        }


        public static void read()
        {
            while (true)
            {
                //_rw.EnterReadLock();
                _rw.EnterWriteLock();
                for (int i = 0; i < _items.Count; i++)
                {
                    Thread.Sleep(1000);
                }
                //_rw.ExitReadLock();
                _rw.ExitWriteLock();
            }
        }


        public static void write(string value)
        {
            while (true)
            {
                int newNumber = GetRandom(100);
                _rw.EnterWriteLock();
                _items.Add(newNumber);
                _rw.ExitWriteLock();
                Console.WriteLine("ThreadID={0} added={1}",Thread.CurrentThread.ManagedThreadId,newNumber);
                Thread.Sleep(100);
            }

        }

        private static int GetRandom(int v)
        {
            lock (_random)
            {
                return _random.Next(v);
            }

        }
    }
vico
  • 17,051
  • 45
  • 159
  • 315
  • You'll have to write a bunch of gritty code to get a set of Monitors to do with RWLS already does. You don't want to write it, there is no joy in having to test it and never being 100% sure that you got it right. – Hans Passant Dec 08 '17 at 13:56

1 Answers1

1

They have different semantics. A Monitor (lock) allows one thread to own the "lock", and that's it. A ReaderWriterLock[Slim] allows any number of readers, or (one writer and nobody else).

So a reader-writer setup might be useful if writes are rare and reads take a non-trivial amount of time, so that you can have multiple concurrent readers, and yet lock everyone out when you need to mutate the data.

Neither is "better". They do different things. They each have scenarios in which they are ideal, and scenarios in which they are poor choices.

Marc Gravell
  • 1,026,079
  • 266
  • 2,566
  • 2,900