From 1f0172cccf16af92adbda49b7e711eba9e2c6edd Mon Sep 17 00:00:00 2001 From: Ben Adams Date: Fri, 14 Oct 2016 16:43:30 +0100 Subject: [PATCH] SpinLock.TryEnter fail fast for timeout 0 --- .../src/System/Threading/SpinLock.cs | 32 ++++++++----------- 1 file changed, 14 insertions(+), 18 deletions(-) diff --git a/src/System.Private.CoreLib/src/System/Threading/SpinLock.cs b/src/System.Private.CoreLib/src/System/Threading/SpinLock.cs index c3a8fb2fe1e..e46ef5faab1 100644 --- a/src/System.Private.CoreLib/src/System/Threading/SpinLock.cs +++ b/src/System.Private.CoreLib/src/System/Threading/SpinLock.cs @@ -324,28 +324,24 @@ private void ContinueTryEnter(int millisecondsTimeout, ref bool lockTaken) observedOwner = m_owner; if ((observedOwner & LOCK_ANONYMOUS_OWNED) == LOCK_UNOWNED) { - if (CompareExchange(ref m_owner, observedOwner | 1, observedOwner, ref lockTaken) == observedOwner) + if (CompareExchange(ref m_owner, observedOwner | 1, observedOwner, ref lockTaken) == observedOwner + || millisecondsTimeout == 0) { + // Aquired lock, or did not aquire lock as owned but timeout is 0 so fail fast return; } } + else if (millisecondsTimeout == 0) + { + // Did not aquire lock as owned and timeout is 0 so fail fast + return; + } else //failed to acquire the lock,then try to update the waiters. If the waiters count reached the maximum, jsut break the loop to avoid overflow { if ((observedOwner & WAITERS_MASK) != MAXIMUM_WAITERS) turn = (Interlocked.Add(ref m_owner, 2) & WAITERS_MASK) >> 1; } - - - // Check the timeout. - if (millisecondsTimeout == 0 || - (millisecondsTimeout != Timeout.Infinite && - TimeoutHelper.UpdateTimeOut(startTime, millisecondsTimeout) <= 0)) - { - DecrementWaiters(); - return; - } - //***Step 2. Spinning //lock acquired failed and waiters updated int processorCount = PlatformHelper.ProcessorCount; @@ -371,13 +367,13 @@ private void ContinueTryEnter(int millisecondsTimeout, ref bool lockTaken) } } } - } - // Check the timeout. - if (millisecondsTimeout != Timeout.Infinite && TimeoutHelper.UpdateTimeOut(startTime, millisecondsTimeout) <= 0) - { - DecrementWaiters(); - return; + // Check the timeout. + if (millisecondsTimeout != Timeout.Infinite && TimeoutHelper.UpdateTimeOut(startTime, millisecondsTimeout) <= 0) + { + DecrementWaiters(); + return; + } } //*** Step 3, Yielding