Revert the CER-like changes made to SpinLock.Enter method and document the problem.
[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         public struct SpinLock
48         {
49                 TicketType ticket;
50
51                 int threadWhoTookLock;
52                 readonly bool isThreadOwnerTrackingEnabled;
53
54                 static Watch sw = Watch.StartNew ();
55
56                 public bool IsThreadOwnerTrackingEnabled {
57                         get {
58                                 return isThreadOwnerTrackingEnabled;
59                         }
60                 }
61
62                 public bool IsHeld {
63                         get {
64                                 // No need for barrier here
65                                 long totalValue = ticket.TotalValue;
66                                 return (totalValue >> 32) != (totalValue & 0xFFFFFFFF);
67                         }
68                 }
69
70                 public bool IsHeldByCurrentThread {
71                         get {
72                                 if (isThreadOwnerTrackingEnabled)
73                                         return IsHeld && Thread.CurrentThread.ManagedThreadId == threadWhoTookLock;
74                                 else
75                                         return IsHeld;
76                         }
77                 }
78
79                 public SpinLock (bool trackId)
80                 {
81                         this.isThreadOwnerTrackingEnabled = trackId;
82                         this.threadWhoTookLock = 0;
83                         this.ticket = new TicketType ();
84                 }
85
86                 [MonoTODO ("Not safe against async exceptions"]
87                 public void Enter (ref bool lockTaken)
88                 {
89                         if (lockTaken)
90                                 throw new ArgumentException ("lockTaken", "lockTaken must be initialized to false");
91                         if (isThreadOwnerTrackingEnabled && IsHeldByCurrentThread)
92                                 throw new LockRecursionException ();
93
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".
100                          */
101                         int slot = Interlocked.Increment (ref ticket.Users) - 1;
102
103                         SpinWait wait = new SpinWait ();
104                         while (slot != ticket.Value)
105                                 wait.SpinOnce ();
106
107                         lockTaken = true;
108                         threadWhoTookLock = Thread.CurrentThread.ManagedThreadId;
109                 }
110
111                 public void TryEnter (ref bool lockTaken)
112                 {
113                         TryEnter (0, ref lockTaken);
114                 }
115
116                 public void TryEnter (TimeSpan timeout, ref bool lockTaken)
117                 {
118                         TryEnter ((int)timeout.TotalMilliseconds, ref lockTaken);
119                 }
120
121                 public void TryEnter (int milliSeconds, ref bool lockTaken)
122                 {
123                         if (milliSeconds < -1)
124                                 throw new ArgumentOutOfRangeException ("milliSeconds", "millisecondsTimeout is a negative number other than -1");
125                         if (lockTaken)
126                                 throw new ArgumentException ("lockTaken", "lockTaken must be initialized to false");
127                         if (isThreadOwnerTrackingEnabled && IsHeldByCurrentThread)
128                                 throw new LockRecursionException ();
129
130                         long start = milliSeconds == -1 ? 0 : sw.ElapsedMilliseconds;
131                         bool stop = false;
132
133                         do {
134                                 long u = ticket.Users;
135                                 long totalValue = (u << 32) | u;
136                                 long newTotalValue
137                                         = BitConverter.IsLittleEndian ? (u << 32) | (u + 1) : ((u + 1) << 32) | u;
138                                 
139                                 RuntimeHelpers.PrepareConstrainedRegions ();
140                                 try {}
141                                 finally {
142                                         lockTaken = Interlocked.CompareExchange (ref ticket.TotalValue, newTotalValue, totalValue) == totalValue;
143                                 
144                                         if (lockTaken) {
145                                                 threadWhoTookLock = Thread.CurrentThread.ManagedThreadId;
146                                                 stop = true;
147                                         }
148                                 }
149                 } while (!stop && (milliSeconds == -1 || (sw.ElapsedMilliseconds - start) < milliSeconds));
150                 }
151
152                 public void Exit ()
153                 {
154                         Exit (false);
155                 }
156
157                 public void Exit (bool flushReleaseWrites)
158                 {
159                         RuntimeHelpers.PrepareConstrainedRegions ();
160                         try {}
161                         finally {
162                                 if (isThreadOwnerTrackingEnabled && !IsHeldByCurrentThread)
163                                         throw new SynchronizationLockException ("Current thread is not the owner of this lock");
164
165                                 threadWhoTookLock = int.MinValue;
166                                 // Fast path
167                                 if (flushReleaseWrites)
168                                         Interlocked.Increment (ref ticket.Value);
169                                 else
170                                         ticket.Value++;
171                         }
172                 }
173         }
174
175         // Wraps a SpinLock in a reference when we need to pass
176         // around the lock
177         internal class SpinLockWrapper
178         {
179                 public SpinLock Lock = new SpinLock (false);
180         }
181 }
182 #endif