DEV Community

Cover image for C# - Reducing Lock Contention with ReaderWriterLockSlim
Keyur Ramoliya
Keyur Ramoliya

Posted on

C# - Reducing Lock Contention with ReaderWriterLockSlim

When you need to synchronize access to a shared resource in a multi-threaded application, you can use ReaderWriterLockSlim to reduce lock contention and improve performance. This class provides a way to allow multiple readers or a single writer to access the resource simultaneously.

using System;
using System.Threading;

class Program
{
    static ReaderWriterLockSlim rwLock = new ReaderWriterLockSlim();
    static int sharedResource = 0;

    static void Main()
    {
        // Start multiple reader and writer threads
        for (int i = 0; i < 5; i++)
        {
            var readerThread = new Thread(ReadSharedResource);
            readerThread.Start();

            var writerThread = new Thread(WriteSharedResource);
            writerThread.Start(i + 1); // Pass a unique writer ID
        }
    }

    static void ReadSharedResource()
    {
        try
        {
            rwLock.EnterReadLock();

            // Simulate reading shared data
            Console.WriteLine($"Reader {Thread.CurrentThread.ManagedThreadId} reads: {sharedResource}");
        }
        finally
        {
            rwLock.ExitReadLock();
        }
    }

    static void WriteSharedResource(object writerId)
    {
        try
        {
            rwLock.EnterWriteLock();

            // Simulate updating shared data
            sharedResource = (int)writerId;
            Console.WriteLine($"Writer {writerId} writes: {sharedResource}");
        }
        finally
        {
            rwLock.ExitWriteLock();
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

In this example:

  1. We create a ReaderWriterLockSlim instance named rwLock to synchronize access to the shared resource, which is an integer named sharedResource.

  2. We start multiple reader and writer threads in the Main method to simulate concurrent access to the shared resource.

  3. The ReadSharedResource method demonstrates how to acquire and release a read lock using rwLock.EnterReadLock() and rwLock.ExitReadLock(), respectively. Multiple reader threads can access the resource simultaneously as long as there are no active writer locks.

  4. The WriteSharedResource method shows how to acquire and release a write lock using rwLock.EnterWriteLock() and rwLock.ExitWriteLock(). Only one writer thread can access the resource at a time, and it blocks reader threads during this time.

By using ReaderWriterLockSlim, you can fine-tune synchronization in your multi-threaded applications. This can significantly reduce lock contention and improve performance when dealing with shared resources that are frequently read but infrequently modified.

Top comments (0)