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 d2d18a444222637556fdbbe11068c4aabdf01c8e..49a092ceed533202ec06a3ad5cf405109579ba06 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 370a5132dc5ecc26526456cdaa1f251050364819..3ee587edc6318c1c66d06ccd00c5a7d423ae9732 100644 (file)
@@ -433,6 +433,25 @@ namespace System.Threading.Tests
             trwl.Dispose();
         }
 
+        [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()
         {