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 public struct SpinLock
51 int threadWhoTookLock;
52 readonly bool isThreadOwnerTrackingEnabled;
54 static Watch sw = Watch.StartNew ();
56 public bool IsThreadOwnerTrackingEnabled {
58 return isThreadOwnerTrackingEnabled;
64 // No need for barrier here
65 long totalValue = ticket.TotalValue;
66 return (totalValue >> 32) != (totalValue & 0xFFFFFFFF);
70 public bool IsHeldByCurrentThread {
72 if (isThreadOwnerTrackingEnabled)
73 return IsHeld && Thread.CurrentThread.ManagedThreadId == threadWhoTookLock;
79 public SpinLock (bool trackId)
81 this.isThreadOwnerTrackingEnabled = trackId;
82 this.threadWhoTookLock = 0;
83 this.ticket = new TicketType ();
86 [MonoTODO ("Not safe against async exceptions"]
87 public void Enter (ref bool lockTaken)
90 throw new ArgumentException ("lockTaken", "lockTaken must be initialized to false");
91 if (isThreadOwnerTrackingEnabled && IsHeldByCurrentThread)
92 throw new LockRecursionException ();
94 /* The current ticket algorithm, even though it's a thing of beauty, doesn't make it easy to
95 * hand back ticket that have been taken in the case of an asynchronous exception and naively
96 * fixing it bloat a code that should be kept simple. A straightforward possibility is to wrap
97 * the whole thing in a finally block but due to the while loop a number of bad things can
98 * happen, thus for the moment the code is left as is in the spirit of "better breaking fast,
99 * than later in a weird way".
101 int slot = Interlocked.Increment (ref ticket.Users) - 1;
103 SpinWait wait = new SpinWait ();
104 while (slot != ticket.Value)
108 threadWhoTookLock = Thread.CurrentThread.ManagedThreadId;
111 public void TryEnter (ref bool lockTaken)
113 TryEnter (0, ref lockTaken);
116 public void TryEnter (TimeSpan timeout, ref bool lockTaken)
118 TryEnter ((int)timeout.TotalMilliseconds, ref lockTaken);
121 public void TryEnter (int milliSeconds, ref bool lockTaken)
123 if (milliSeconds < -1)
124 throw new ArgumentOutOfRangeException ("milliSeconds", "millisecondsTimeout is a negative number other than -1");
126 throw new ArgumentException ("lockTaken", "lockTaken must be initialized to false");
127 if (isThreadOwnerTrackingEnabled && IsHeldByCurrentThread)
128 throw new LockRecursionException ();
130 long start = milliSeconds == -1 ? 0 : sw.ElapsedMilliseconds;
134 long u = ticket.Users;
135 long totalValue = (u << 32) | u;
137 = BitConverter.IsLittleEndian ? (u << 32) | (u + 1) : ((u + 1) << 32) | u;
139 RuntimeHelpers.PrepareConstrainedRegions ();
142 lockTaken = Interlocked.CompareExchange (ref ticket.TotalValue, newTotalValue, totalValue) == totalValue;
145 threadWhoTookLock = Thread.CurrentThread.ManagedThreadId;
149 } while (!stop && (milliSeconds == -1 || (sw.ElapsedMilliseconds - start) < milliSeconds));
157 public void Exit (bool flushReleaseWrites)
159 RuntimeHelpers.PrepareConstrainedRegions ();
162 if (isThreadOwnerTrackingEnabled && !IsHeldByCurrentThread)
163 throw new SynchronizationLockException ("Current thread is not the owner of this lock");
165 threadWhoTookLock = int.MinValue;
167 if (flushReleaseWrites)
168 Interlocked.Increment (ref ticket.Value);
175 // Wraps a SpinLock in a reference when we need to pass
177 internal class SpinLockWrapper
179 public SpinLock Lock = new SpinLock (false);