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();
}
}
}
In this example:
We create a
ReaderWriterLockSlim
instance namedrwLock
to synchronize access to the shared resource, which is an integer namedsharedResource
.We start multiple reader and writer threads in the
Main
method to simulate concurrent access to the shared resource.The
ReadSharedResource
method demonstrates how to acquire and release a read lock usingrwLock.EnterReadLock()
andrwLock.ExitReadLock()
, respectively. Multiple reader threads can access the resource simultaneously as long as there are no active writer locks.The
WriteSharedResource
method shows how to acquire and release a write lock usingrwLock.EnterWriteLock()
andrwLock.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)