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
28 using System.Collections.Concurrent;
29 using System.Runtime.ConstrainedExecution;
30 using System.Runtime.InteropServices;
31 using System.Runtime.CompilerServices;
33 namespace System.Threading
35 [StructLayout(LayoutKind.Explicit)]
36 internal struct TicketType {
38 public long TotalValue;
45 /* Implement the ticket SpinLock algorithm described on http://locklessinc.com/articles/locks/
46 * This lock is usable on both endianness.
47 * All the try/finally patterns in this class and various extra gimmicks compared to the original
48 * algorithm are here to avoid problems caused by asynchronous exceptions.
50 [System.Diagnostics.DebuggerDisplay ("IsHeld = {IsHeld}")]
51 [System.Diagnostics.DebuggerTypeProxy ("System.Threading.SpinLock+SystemThreading_SpinLockDebugView")]
52 public struct SpinLock
56 int threadWhoTookLock;
57 readonly bool isThreadOwnerTrackingEnabled;
59 static Watch sw = Watch.StartNew ();
61 ConcurrentOrderedList<int> stallTickets;
63 public bool IsThreadOwnerTrackingEnabled {
65 return isThreadOwnerTrackingEnabled;
71 // No need for barrier here
72 long totalValue = ticket.TotalValue;
73 return (totalValue >> 32) != (totalValue & 0xFFFFFFFF);
77 public bool IsHeldByCurrentThread {
79 if (isThreadOwnerTrackingEnabled)
80 return IsHeld && Thread.CurrentThread.ManagedThreadId == threadWhoTookLock;
86 public SpinLock (bool enableThreadOwnerTracking)
88 this.isThreadOwnerTrackingEnabled = enableThreadOwnerTracking;
89 this.threadWhoTookLock = 0;
90 this.ticket = new TicketType ();
91 this.stallTickets = null;
94 [MonoTODO ("Not safe against async exceptions")]
95 public void Enter (ref bool lockTaken)
98 throw new ArgumentException ("lockTaken", "lockTaken must be initialized to false");
99 if (isThreadOwnerTrackingEnabled && IsHeldByCurrentThread)
100 throw new LockRecursionException ();
104 RuntimeHelpers.PrepareConstrainedRegions ();
106 slot = Interlocked.Increment (ref ticket.Users) - 1;
108 SpinWait wait = new SpinWait ();
109 while (slot != ticket.Value) {
112 while (stallTickets != null && stallTickets.TryRemove (ticket.Value))
116 if (slot == ticket.Value) {
118 threadWhoTookLock = Thread.CurrentThread.ManagedThreadId;
119 } else if (slot != -1) {
120 // We have been interrupted, initialize stallTickets
121 if (stallTickets == null)
122 Interlocked.CompareExchange (ref stallTickets, new ConcurrentOrderedList<int> (), null);
123 stallTickets.TryAdd (slot);
128 public void TryEnter (ref bool lockTaken)
130 TryEnter (0, ref lockTaken);
133 public void TryEnter (TimeSpan timeout, ref bool lockTaken)
135 TryEnter ((int)timeout.TotalMilliseconds, ref lockTaken);
138 public void TryEnter (int millisecondsTimeout, ref bool lockTaken)
140 if (millisecondsTimeout < -1)
141 throw new ArgumentOutOfRangeException ("milliSeconds", "millisecondsTimeout is a negative number other than -1");
143 throw new ArgumentException ("lockTaken", "lockTaken must be initialized to false");
144 if (isThreadOwnerTrackingEnabled && IsHeldByCurrentThread)
145 throw new LockRecursionException ();
147 long start = millisecondsTimeout == -1 ? 0 : sw.ElapsedMilliseconds;
151 while (stallTickets != null && stallTickets.TryRemove (ticket.Value))
154 long u = ticket.Users;
155 long totalValue = (u << 32) | u;
157 = BitConverter.IsLittleEndian ? (u << 32) | (u + 1) : ((u + 1) << 32) | u;
159 RuntimeHelpers.PrepareConstrainedRegions ();
162 lockTaken = Interlocked.CompareExchange (ref ticket.TotalValue, newTotalValue, totalValue) == totalValue;
165 threadWhoTookLock = Thread.CurrentThread.ManagedThreadId;
169 } while (!stop && (millisecondsTimeout == -1 || (sw.ElapsedMilliseconds - start) < millisecondsTimeout));
172 [ReliabilityContract (Consistency.WillNotCorruptState, Cer.Success)]
178 [ReliabilityContract (Consistency.WillNotCorruptState, Cer.Success)]
179 public void Exit (bool useMemoryBarrier)
181 RuntimeHelpers.PrepareConstrainedRegions ();
184 if (isThreadOwnerTrackingEnabled && !IsHeldByCurrentThread)
185 throw new SynchronizationLockException ("Current thread is not the owner of this lock");
187 threadWhoTookLock = int.MinValue;
189 if (useMemoryBarrier)
190 Interlocked.Increment (ref ticket.Value);
193 } while (stallTickets != null && stallTickets.TryRemove (ticket.Value));
198 // Wraps a SpinLock in a reference when we need to pass
200 internal class SpinLockWrapper
202 public SpinLock Lock = new SpinLock (false);