122a3f094b2debef171d29b4646e58336acb5d63
[mono.git] / mcs / class / corlib / System.Threading / SpinLock.cs
1 // SpinLock.cs
2 //
3 // Copyright (c) 2008 Jérémie "Garuma" Laval
4 //
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:
11 //
12 // The above copyright notice and this permission notice shall be included in
13 // all copies or substantial portions of the Software.
14 //
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
21 // THE SOFTWARE.
22 //
23 //
24
25 using System;
26 using System.Runtime.ConstrainedExecution;
27 using System.Runtime.InteropServices;
28 using System.Runtime.CompilerServices;
29
30 #if NET_4_0 || BOOTSTRAP_NET_4_0
31
32 namespace System.Threading
33 {
34         [StructLayout(LayoutKind.Explicit)]
35         internal struct TicketType {
36                 [FieldOffset(0)]
37                 public long TotalValue;
38                 [FieldOffset(0)]
39                 public int Value;
40                 [FieldOffset(4)]
41                 public int Users;
42         }
43
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
50         {
51                 TicketType ticket;
52
53                 int threadWhoTookLock;
54                 readonly bool isThreadOwnerTrackingEnabled;
55
56                 static Watch sw = Watch.StartNew ();
57
58                 public bool IsThreadOwnerTrackingEnabled {
59                         get {
60                                 return isThreadOwnerTrackingEnabled;
61                         }
62                 }
63
64                 public bool IsHeld {
65                         get {
66                                 // No need for barrier here
67                                 long totalValue = ticket.TotalValue;
68                                 return (totalValue >> 32) != (totalValue & 0xFFFFFFFF);
69                         }
70                 }
71
72                 public bool IsHeldByCurrentThread {
73                         get {
74                                 if (isThreadOwnerTrackingEnabled)
75                                         return IsHeld && Thread.CurrentThread.ManagedThreadId == threadWhoTookLock;
76                                 else
77                                         return IsHeld;
78                         }
79                 }
80
81                 public SpinLock (bool enableThreadOwnerTracking)
82                 {
83                         this.isThreadOwnerTrackingEnabled = enableThreadOwnerTracking;
84                         this.threadWhoTookLock = 0;
85                         this.ticket = new TicketType ();
86                 }
87
88                 [MonoTODO ("Not safe against async exceptions")]
89                 public void Enter (ref bool lockTaken)
90                 {
91                         if (lockTaken)
92                                 throw new ArgumentException ("lockTaken", "lockTaken must be initialized to false");
93                         if (isThreadOwnerTrackingEnabled && IsHeldByCurrentThread)
94                                 throw new LockRecursionException ();
95
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".
102                          */
103                         int slot = Interlocked.Increment (ref ticket.Users) - 1;
104
105                         SpinWait wait = new SpinWait ();
106                         while (slot != ticket.Value)
107                                 wait.SpinOnce ();
108
109                         lockTaken = true;
110                         threadWhoTookLock = Thread.CurrentThread.ManagedThreadId;
111                 }
112
113                 public void TryEnter (ref bool lockTaken)
114                 {
115                         TryEnter (0, ref lockTaken);
116                 }
117
118                 public void TryEnter (TimeSpan timeout, ref bool lockTaken)
119                 {
120                         TryEnter ((int)timeout.TotalMilliseconds, ref lockTaken);
121                 }
122
123                 public void TryEnter (int millisecondsTimeout, ref bool lockTaken)
124                 {
125                         if (millisecondsTimeout < -1)
126                                 throw new ArgumentOutOfRangeException ("milliSeconds", "millisecondsTimeout is a negative number other than -1");
127                         if (lockTaken)
128                                 throw new ArgumentException ("lockTaken", "lockTaken must be initialized to false");
129                         if (isThreadOwnerTrackingEnabled && IsHeldByCurrentThread)
130                                 throw new LockRecursionException ();
131
132                         long start = millisecondsTimeout == -1 ? 0 : sw.ElapsedMilliseconds;
133                         bool stop = false;
134
135                         do {
136                                 long u = ticket.Users;
137                                 long totalValue = (u << 32) | u;
138                                 long newTotalValue
139                                         = BitConverter.IsLittleEndian ? (u << 32) | (u + 1) : ((u + 1) << 32) | u;
140                                 
141                                 RuntimeHelpers.PrepareConstrainedRegions ();
142                                 try {}
143                                 finally {
144                                         lockTaken = Interlocked.CompareExchange (ref ticket.TotalValue, newTotalValue, totalValue) == totalValue;
145                                 
146                                         if (lockTaken) {
147                                                 threadWhoTookLock = Thread.CurrentThread.ManagedThreadId;
148                                                 stop = true;
149                                         }
150                                 }
151                 } while (!stop && (millisecondsTimeout == -1 || (sw.ElapsedMilliseconds - start) < millisecondsTimeout));
152                 }
153
154                 public void Exit ()
155                 {
156                         Exit (false);
157                 }
158
159                 [ReliabilityContract (Consistency.WillNotCorruptState, Cer.Success)]
160                 public void Exit (bool useMemoryBarrier)
161                 {
162                         RuntimeHelpers.PrepareConstrainedRegions ();
163                         try {}
164                         finally {
165                                 if (isThreadOwnerTrackingEnabled && !IsHeldByCurrentThread)
166                                         throw new SynchronizationLockException ("Current thread is not the owner of this lock");
167
168                                 threadWhoTookLock = int.MinValue;
169                                 // Fast path
170                                 if (useMemoryBarrier)
171                                         Interlocked.Increment (ref ticket.Value);
172                                 else
173                                         ticket.Value++;
174                         }
175                 }
176         }
177
178         // Wraps a SpinLock in a reference when we need to pass
179         // around the lock
180         internal class SpinLockWrapper
181         {
182                 public SpinLock Lock = new SpinLock (false);
183         }
184 }
185 #endif