From cee712105850ac3385cd0091a923438167433f9f Mon Sep 17 00:00:00 2001
From: TSR Berry <20988865+TSRBerry@users.noreply.github.com>
Date: Sat, 8 Apr 2023 01:22:00 +0200
Subject: Move solution and projects to src
---
.../Memory/PartialUnmaps/NativeReaderWriterLock.cs | 80 ++++++++++++++++++++++
1 file changed, 80 insertions(+)
create mode 100644 src/Ryujinx.Common/Memory/PartialUnmaps/NativeReaderWriterLock.cs
(limited to 'src/Ryujinx.Common/Memory/PartialUnmaps/NativeReaderWriterLock.cs')
diff --git a/src/Ryujinx.Common/Memory/PartialUnmaps/NativeReaderWriterLock.cs b/src/Ryujinx.Common/Memory/PartialUnmaps/NativeReaderWriterLock.cs
new file mode 100644
index 00000000..78eeb16f
--- /dev/null
+++ b/src/Ryujinx.Common/Memory/PartialUnmaps/NativeReaderWriterLock.cs
@@ -0,0 +1,80 @@
+using System.Runtime.InteropServices;
+using System.Threading;
+
+using static Ryujinx.Common.Memory.PartialUnmaps.PartialUnmapHelpers;
+
+namespace Ryujinx.Common.Memory.PartialUnmaps
+{
+ ///
+ /// A simple implementation of a ReaderWriterLock which can be used from native code.
+ ///
+ [StructLayout(LayoutKind.Sequential, Pack = 4)]
+ public struct NativeReaderWriterLock
+ {
+ public int WriteLock;
+ public int ReaderCount;
+
+ public static int WriteLockOffset;
+ public static int ReaderCountOffset;
+
+ ///
+ /// Populates the field offsets for use when emitting native code.
+ ///
+ static NativeReaderWriterLock()
+ {
+ NativeReaderWriterLock instance = new NativeReaderWriterLock();
+
+ WriteLockOffset = OffsetOf(ref instance, ref instance.WriteLock);
+ ReaderCountOffset = OffsetOf(ref instance, ref instance.ReaderCount);
+ }
+
+ ///
+ /// Acquires the reader lock.
+ ///
+ public void AcquireReaderLock()
+ {
+ // Must take write lock for a very short time to become a reader.
+
+ while (Interlocked.CompareExchange(ref WriteLock, 1, 0) != 0) { }
+
+ Interlocked.Increment(ref ReaderCount);
+
+ Interlocked.Exchange(ref WriteLock, 0);
+ }
+
+ ///
+ /// Releases the reader lock.
+ ///
+ public void ReleaseReaderLock()
+ {
+ Interlocked.Decrement(ref ReaderCount);
+ }
+
+ ///
+ /// Upgrades to a writer lock. The reader lock is temporarily released while obtaining the writer lock.
+ ///
+ public void UpgradeToWriterLock()
+ {
+ // Prevent any more threads from entering reader.
+ // If the write lock is already taken, wait for it to not be taken.
+
+ Interlocked.Decrement(ref ReaderCount);
+
+ while (Interlocked.CompareExchange(ref WriteLock, 1, 0) != 0) { }
+
+ // Wait for reader count to drop to 0, then take the lock again as the only reader.
+
+ while (Interlocked.CompareExchange(ref ReaderCount, 1, 0) != 0) { }
+ }
+
+ ///
+ /// Downgrades from a writer lock, back to a reader one.
+ ///
+ public void DowngradeFromWriterLock()
+ {
+ // Release the WriteLock.
+
+ Interlocked.Exchange(ref WriteLock, 0);
+ }
+ }
+}
--
cgit v1.2.3