-
Notifications
You must be signed in to change notification settings - Fork 1
/
ReaderWriterLock.cs
50 lines (45 loc) · 1.46 KB
/
ReaderWriterLock.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
using System.Threading;
namespace AlgorithmsAndDataStructures.DataStructures.Concurrency
{
#pragma warning disable CA1001 // Types that own disposable fields should be disposable
public class ReaderWriterLock
#pragma warning restore CA1001 // Types that own disposable fields should be disposable
{
private readonly Semaphore writerSemaphore = new Semaphore(1, 1);
private volatile int readersCounter;
private readonly Mutex readersMutex = new Mutex();
private readonly Mutex readersCounterMutex = new Mutex();
public void AcquireReaderLock()
{
readersMutex.WaitOne();
readersCounterMutex.WaitOne();
readersCounter++;
if (readersCounter == 1)
{
writerSemaphore.WaitOne();
}
readersCounterMutex.ReleaseMutex();
readersMutex.ReleaseMutex();
}
public void ReleaseReaderLock()
{
readersCounterMutex.WaitOne();
readersCounter--;
if (readersCounter == 0)
{
writerSemaphore.Release();
}
readersCounterMutex.ReleaseMutex();
}
public void AcquireWriterLock()
{
readersMutex.WaitOne();
writerSemaphore.WaitOne();
}
public void ReleaseWriterLock()
{
writerSemaphore.Release();
readersMutex.ReleaseMutex();
}
}
}