3 // Copyright (c) 2008 Jérémie "Garuma" Laval
5 // Permission is hereby granted, free of charge, to any person obtaining a copy
6 // of this software and associated documentation files (the "Software"), to deal
7 // in the Software without restriction, including without limitation the rights
8 // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9 // copies of the Software, and to permit persons to whom the Software is
10 // furnished to do so, subject to the following conditions:
12 // The above copyright notice and this permission notice shall be included in
13 // all copies or substantial portions of the Software.
15 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
26 using System.Runtime.ConstrainedExecution;
27 using System.Runtime.InteropServices;
28 using System.Runtime.CompilerServices;
30 #if NET_4_0 || BOOTSTRAP_NET_4_0
32 namespace System.Threading
34 [StructLayout(LayoutKind.Explicit)]
35 internal struct TicketType {
37 public long TotalValue;
44 // Implement the ticket SpinLock algorithm described on http://locklessinc.com/articles/locks/
45 // This lock is usable on both endianness
46 // TODO: some 32 bits platform apparently doesn't support CAS with 64 bits value
47 [System.Diagnostics.DebuggerDisplay ("IsHeld = {IsHeld}")]
48 [System.Diagnostics.DebuggerTypeProxy ("System.Threading.SpinLock+SystemThreading_SpinLockDebugView")]
49 public struct SpinLock
53 int threadWhoTookLock;
54 readonly bool isThreadOwnerTrackingEnabled;
56 static Watch sw = Watch.StartNew ();
58 public bool IsThreadOwnerTrackingEnabled {
60 return isThreadOwnerTrackingEnabled;
66 // No need for barrier here
67 long totalValue = ticket.TotalValue;
68 return (totalValue >> 32) != (totalValue & 0xFFFFFFFF);
72 public bool IsHeldByCurrentThread {
74 if (isThreadOwnerTrackingEnabled)
75 return IsHeld && Thread.CurrentThread.ManagedThreadId == threadWhoTookLock;
81 public SpinLock (bool enableThreadOwnerTracking)
83 this.isThreadOwnerTrackingEnabled = enableThreadOwnerTracking;
84 this.threadWhoTookLock = 0;
85 this.ticket = new TicketType ();
88 [MonoTODO ("Not safe against async exceptions")]
89 public void Enter (ref bool lockTaken)
92 throw new ArgumentException ("lockTaken", "lockTaken must be initialized to false");
93 if (isThreadOwnerTrackingEnabled && IsHeldByCurrentThread)
94 throw new LockRecursionException ();
96 /* The current ticket algorithm, even though it's a thing of beauty, doesn't make it easy to
97 * hand back ticket that have been taken in the case of an asynchronous exception and naively
98 * fixing it bloat a code that should be kept simple. A straightforward possibility is to wrap
99 * the whole thing in a finally block but due to the while loop a number of bad things can
100 * happen, thus for the moment the code is left as is in the spirit of "better breaking fast,
101 * than later in a weird way".
103 int slot = Interlocked.Increment (ref ticket.Users) - 1;
105 SpinWait wait = new SpinWait ();
106 while (slot != ticket.Value)
110 threadWhoTookLock = Thread.CurrentThread.ManagedThreadId;
113 public void TryEnter (ref bool lockTaken)
115 TryEnter (0, ref lockTaken);
118 public void TryEnter (TimeSpan timeout, ref bool lockTaken)
120 TryEnter ((int)timeout.TotalMilliseconds, ref lockTaken);
123 public void TryEnter (int millisecondsTimeout, ref bool lockTaken)
125 if (millisecondsTimeout < -1)
126 throw new ArgumentOutOfRangeException ("milliSeconds", "millisecondsTimeout is a negative number other than -1");
128 throw new ArgumentException ("lockTaken", "lockTaken must be initialized to false");
129 if (isThreadOwnerTrackingEnabled && IsHeldByCurrentThread)
130 throw new LockRecursionException ();
132 long start = millisecondsTimeout == -1 ? 0 : sw.ElapsedMilliseconds;
136 long u = ticket.Users;
137 long totalValue = (u << 32) | u;
139 = BitConverter.IsLittleEndian ? (u << 32) | (u + 1) : ((u + 1) << 32) | u;
141 RuntimeHelpers.PrepareConstrainedRegions ();
144 lockTaken = Interlocked.CompareExchange (ref ticket.TotalValue, newTotalValue, totalValue) == totalValue;
147 threadWhoTookLock = Thread.CurrentThread.ManagedThreadId;
151 } while (!stop && (millisecondsTimeout == -1 || (sw.ElapsedMilliseconds - start) < millisecondsTimeout));
159 [ReliabilityContract (Consistency.WillNotCorruptState, Cer.Success)]
160 public void Exit (bool useMemoryBarrier)
162 RuntimeHelpers.PrepareConstrainedRegions ();
165 if (isThreadOwnerTrackingEnabled && !IsHeldByCurrentThread)
166 throw new SynchronizationLockException ("Current thread is not the owner of this lock");
168 threadWhoTookLock = int.MinValue;
170 if (useMemoryBarrier)
171 Interlocked.Increment (ref ticket.Value);
178 // Wraps a SpinLock in a reference when we need to pass
180 internal class SpinLockWrapper
182 public SpinLock Lock = new SpinLock (false);