DEV Community

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

Posted on

2

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.

Image of Datadog

The Future of AI, LLMs, and Observability on Google Cloud

Datadog sat down with Google’s Director of AI to discuss the current and future states of AI, ML, and LLMs on Google Cloud. Discover 7 key insights for technical leaders, covering everything from upskilling teams to observability best practices

Learn More

Top comments (0)

The Most Contextual AI Development Assistant

Pieces.app image

Our centralized storage agent works on-device, unifying various developer tools to proactively capture and enrich useful materials, streamline collaboration, and solve complex problems through a contextual understanding of your unique workflow.

👥 Ideal for solo developers, teams, and cross-company projects

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay