Further .NET 4.0 ification of the mobile profile
[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 #if NET_4_0
26
27 using System;
28 using System.Collections.Concurrent;
29 using System.Runtime.ConstrainedExecution;
30 using System.Runtime.InteropServices;
31 using System.Runtime.CompilerServices;
32
33 namespace System.Threading
34 {
35         [StructLayout(LayoutKind.Explicit)]
36         internal struct TicketType {
37                 [FieldOffset(0)]
38                 public long TotalValue;
39                 [FieldOffset(0)]
40                 public int Value;
41                 [FieldOffset(4)]
42                 public int Users;
43         }
44
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.
49          */
50         [System.Diagnostics.DebuggerDisplay ("IsHeld = {IsHeld}")]
51         [System.Diagnostics.DebuggerTypeProxy ("System.Threading.SpinLock+SystemThreading_SpinLockDebugView")]
52         public struct SpinLock
53         {
54                 TicketType ticket;
55
56                 int threadWhoTookLock;
57                 readonly bool isThreadOwnerTrackingEnabled;
58
59                 static Watch sw = Watch.StartNew ();
60
61                 ConcurrentOrderedList<int> stallTickets;
62
63                 public bool IsThreadOwnerTrackingEnabled {
64                         get {
65                                 return isThreadOwnerTrackingEnabled;
66                         }
67                 }
68
69                 public bool IsHeld {
70                         get {
71                                 // No need for barrier here
72                                 long totalValue = ticket.TotalValue;
73                                 return (totalValue >> 32) != (totalValue & 0xFFFFFFFF);
74                         }
75                 }
76
77                 public bool IsHeldByCurrentThread {
78                         get {
79                                 if (isThreadOwnerTrackingEnabled)
80                                         return IsHeld && Thread.CurrentThread.ManagedThreadId == threadWhoTookLock;
81                                 else
82                                         return IsHeld;
83                         }
84                 }
85
86                 public SpinLock (bool enableThreadOwnerTracking)
87                 {
88                         this.isThreadOwnerTrackingEnabled = enableThreadOwnerTracking;
89                         this.threadWhoTookLock = 0;
90                         this.ticket = new TicketType ();
91                         this.stallTickets = null;
92                 }
93
94                 [MonoTODO ("Not safe against async exceptions")]
95                 public void Enter (ref bool lockTaken)
96                 {
97                         if (lockTaken)
98                                 throw new ArgumentException ("lockTaken", "lockTaken must be initialized to false");
99                         if (isThreadOwnerTrackingEnabled && IsHeldByCurrentThread)
100                                 throw new LockRecursionException ();
101
102                         int slot = -1;
103
104                         RuntimeHelpers.PrepareConstrainedRegions ();
105                         try {
106                                 slot = Interlocked.Increment (ref ticket.Users) - 1;
107
108                                 SpinWait wait = new SpinWait ();
109                                 while (slot != ticket.Value) {
110                                         wait.SpinOnce ();
111
112                                         while (stallTickets != null && stallTickets.TryRemove (ticket.Value))
113                                                 ++ticket.Value;
114                                 }
115                         } finally {
116                                 if (slot == ticket.Value) {
117                                         lockTaken = true;
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);
124                                 }
125                         }
126                 }
127
128                 public void TryEnter (ref bool lockTaken)
129                 {
130                         TryEnter (0, ref lockTaken);
131                 }
132
133                 public void TryEnter (TimeSpan timeout, ref bool lockTaken)
134                 {
135                         TryEnter ((int)timeout.TotalMilliseconds, ref lockTaken);
136                 }
137
138                 public void TryEnter (int millisecondsTimeout, ref bool lockTaken)
139                 {
140                         if (millisecondsTimeout < -1)
141                                 throw new ArgumentOutOfRangeException ("milliSeconds", "millisecondsTimeout is a negative number other than -1");
142                         if (lockTaken)
143                                 throw new ArgumentException ("lockTaken", "lockTaken must be initialized to false");
144                         if (isThreadOwnerTrackingEnabled && IsHeldByCurrentThread)
145                                 throw new LockRecursionException ();
146
147                         long start = millisecondsTimeout == -1 ? 0 : sw.ElapsedMilliseconds;
148                         bool stop = false;
149
150                         do {
151                                 while (stallTickets != null && stallTickets.TryRemove (ticket.Value))
152                                         ++ticket.Value;
153
154                                 long u = ticket.Users;
155                                 long totalValue = (u << 32) | u;
156                                 long newTotalValue
157                                         = BitConverter.IsLittleEndian ? (u << 32) | (u + 1) : ((u + 1) << 32) | u;
158                                 
159                                 RuntimeHelpers.PrepareConstrainedRegions ();
160                                 try {}
161                                 finally {
162                                         lockTaken = Interlocked.CompareExchange (ref ticket.TotalValue, newTotalValue, totalValue) == totalValue;
163                                 
164                                         if (lockTaken) {
165                                                 threadWhoTookLock = Thread.CurrentThread.ManagedThreadId;
166                                                 stop = true;
167                                         }
168                                 }
169                 } while (!stop && (millisecondsTimeout == -1 || (sw.ElapsedMilliseconds - start) < millisecondsTimeout));
170                 }
171
172                 [ReliabilityContract (Consistency.WillNotCorruptState, Cer.Success)]
173                 public void Exit ()
174                 {
175                         Exit (false);
176                 }
177
178                 [ReliabilityContract (Consistency.WillNotCorruptState, Cer.Success)]
179                 public void Exit (bool useMemoryBarrier)
180                 {
181                         RuntimeHelpers.PrepareConstrainedRegions ();
182                         try {}
183                         finally {
184                                 if (isThreadOwnerTrackingEnabled && !IsHeldByCurrentThread)
185                                         throw new SynchronizationLockException ("Current thread is not the owner of this lock");
186
187                                 threadWhoTookLock = int.MinValue;
188                                 do {
189                                         if (useMemoryBarrier)
190                                                 Interlocked.Increment (ref ticket.Value);
191                                         else
192                                                 ticket.Value++;
193                                 } while (stallTickets != null && stallTickets.TryRemove (ticket.Value));
194                         }
195                 }
196         }
197
198         // Wraps a SpinLock in a reference when we need to pass
199         // around the lock
200         internal class SpinLockWrapper
201         {
202                 public SpinLock Lock = new SpinLock (false);
203         }
204 }
205 #endif