Skip to content

Instantly share code, notes, and snippets.

@NonymousMorlock
Created January 17, 2023 12:16
Show Gist options
  • Save NonymousMorlock/b9c0f3ac4d81624c3c773ab2cf40b73e to your computer and use it in GitHub Desktop.
Save NonymousMorlock/b9c0f3ac4d81624c3c773ab2cf40b73e to your computer and use it in GitHub Desktop.
using System;
using System.Threading;
class Program
{
static int data = 0;
static ReaderWriterLock rwlock = new ReaderWriterLock();
static void Main(string[] args)
{
new Thread(Read).Start();
new Thread(Read).Start();
new Thread(Write).Start('A');
new Thread(Write).Start('B');
}
static void Read()
{
rwlock.AcquireReaderLock(Timeout.Infinite);
try
{
Console.WriteLine($"Reading data: {data}");
} finally
{
rwlock.ReleaseReaderLock();
}
}
static void Write(object threadID)
{
rwlock.AcquireWriterLock(Timeout.Infinite);
try
{
data++;
Console.WriteLine($"Writing data: {data} (Thread {threadID})");
} finally
{
rwlock.ReleaseWriterLock();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment