Fix ReaderWriterLock when using it in recursive scenarios and multiple instances...
authorEduardo Velarde <32459232+eduardo-vp@users.noreply.github.com>
Wed, 1 Feb 2023 18:03:25 +0000 (10:03 -0800)
committerGitHub <noreply@github.com>
Wed, 1 Feb 2023 18:03:25 +0000 (10:03 -0800)
---------

Co-authored-by: Eduardo Manuel Velarde Polar <evelardepola@microsoft.com>
src/libraries/System.Threading/src/System/Threading/ReaderWriterLock.cs
src/libraries/System.Threading/tests/ReaderWriterLockTests.cs

index d2d18a4..49a092c 100644 (file)
@@ -1256,20 +1256,10 @@ namespace System.Threading
                 Debug.Assert(lockID != 0);
 
                 ThreadLocalLockEntry? headEntry = t_lockEntryHead;
-                if (headEntry != null)
+                if (headEntry != null && headEntry._lockID == lockID)
                 {
-                    if (headEntry._lockID == lockID)
-                    {
-                        VerifyNoNonemptyEntryInListAfter(lockID, headEntry);
-                        return headEntry;
-                    }
-
-                    if (headEntry.IsFree)
-                    {
-                        VerifyNoNonemptyEntryInListAfter(lockID, headEntry);
-                        headEntry._lockID = lockID;
-                        return headEntry;
-                    }
+                    VerifyNoNonemptyEntryInListAfter(lockID, headEntry);
+                    return headEntry;
                 }
 
                 return GetOrCreateCurrentSlow(lockID, headEntry);
index 370a513..3ee587e 100644 (file)
@@ -434,6 +434,25 @@ namespace System.Threading.Tests
         }
 
         [Fact]
+        public static void MultipleNestedReadersMiscellaneousTest()
+        {
+            var trwl1 = new TestReaderWriterLock();
+            var trwl2 = new TestReaderWriterLock();
+
+            trwl1.AcquireReaderLock();
+
+            trwl2.AcquireReaderLock();
+            trwl2.ReleaseReaderLock();
+
+            trwl1.AcquireReaderLock();
+            trwl1.ReleaseReaderLock();
+            trwl1.ReleaseReaderLock();
+
+            trwl1.Dispose();
+            trwl2.Dispose();
+        }
+
+        [Fact]
         public static void DowngradeQuirks_ChangedInDotNetCore()
         {
             var trwl = new TestReaderWriterLock();