SpinLock performance improvements
[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
29 #if NET_4_0 || BOOTSTRAP_NET_4_0
30 namespace System.Threading
31 {
32         [StructLayout(LayoutKind.Explicit)]
33         internal struct TicketType {
34                 [FieldOffset(0)]
35                 public long TotalValue;
36                 [FieldOffset(0)]
37                 public int Value;
38                 [FieldOffset(4)]
39                 public int Users;
40         }
41
42         // Implement the ticket SpinLock algorithm described on http://locklessinc.com/articles/locks/
43         // This lock is usable on both endianness
44         // TODO: some 32 bits platform apparently doesn't support CAS with 64 bits value
45         public struct SpinLock
46         {
47                 TicketType ticket;
48
49                 int threadWhoTookLock;
50                 readonly bool isThreadOwnerTrackingEnabled;
51
52                 static Watch sw = Watch.StartNew ();
53
54                 public bool IsThreadOwnerTrackingEnabled {
55                         get {
56                                 return isThreadOwnerTrackingEnabled;
57                         }
58                 }
59
60                 public bool IsHeld {
61                         get {
62                                 // No need for barrier here
63                                 long totalValue = ticket.TotalValue;
64                                 return (totalValue >> 32) != (totalValue & 0xFFFFFFFF);
65                         }
66                 }
67
68                 public bool IsHeldByCurrentThread {
69                         get {
70                                 if (isThreadOwnerTrackingEnabled)
71                                         return IsHeld && Thread.CurrentThread.ManagedThreadId == threadWhoTookLock;
72                                 else
73                                         return IsHeld;
74                         }
75                 }
76
77                 public SpinLock (bool trackId)
78                 {
79                         this.isThreadOwnerTrackingEnabled = trackId;
80                         this.threadWhoTookLock = 0;
81                         this.ticket = new TicketType ();
82                 }
83
84                 [MonoTODO("This method is not rigorously correct. Need CER treatment")]
85                 public void Enter (ref bool lockTaken)
86                 {
87                         if (lockTaken)
88                                 throw new ArgumentException ("lockTaken", "lockTaken must be initialized to false");
89                         if (isThreadOwnerTrackingEnabled && IsHeldByCurrentThread)
90                                 throw new LockRecursionException ();
91
92                         int slot = Interlocked.Increment (ref ticket.Users) - 1;
93
94                         SpinWait wait = new SpinWait ();
95                         while (slot != ticket.Value)
96                                 wait.SpinOnce ();
97                         
98                         lockTaken = true;
99                         
100                         threadWhoTookLock = Thread.CurrentThread.ManagedThreadId;
101                 }
102
103                 [MonoTODO("This method is not rigorously correct. Need CER treatment")]
104                 public void TryEnter (ref bool lockTaken)
105                 {
106                         TryEnter (0, ref lockTaken);
107                 }
108
109                 [MonoTODO("This method is not rigorously correct. Need CER treatment")]
110                 public void TryEnter (TimeSpan timeout, ref bool lockTaken)
111                 {
112                         TryEnter ((int)timeout.TotalMilliseconds, ref lockTaken);
113                 }
114
115                 [MonoTODO("This method is not rigorously correct. Need CER treatment")]
116                 public void TryEnter (int milliSeconds, ref bool lockTaken)
117                 {
118                         if (milliSeconds < -1)
119                                 throw new ArgumentOutOfRangeException ("milliSeconds", "millisecondsTimeout is a negative number other than -1");
120                         if (lockTaken)
121                                 throw new ArgumentException ("lockTaken", "lockTaken must be initialized to false");
122                         if (isThreadOwnerTrackingEnabled && IsHeldByCurrentThread)
123                                 throw new LockRecursionException ();
124
125                         long start = milliSeconds == -1 ? 0 : sw.ElapsedMilliseconds;
126
127                         do {
128                                 long u = ticket.Users;
129                                 long totalValue = (u << 32) | u;
130                                 long newTotalValue
131                                         = BitConverter.IsLittleEndian ? (u << 32) | (u + 1) : ((u + 1) << 32) | u;
132                                 
133                                 lockTaken = Interlocked.CompareExchange (ref ticket.TotalValue, newTotalValue, totalValue) == totalValue;
134                                 
135                                 if (lockTaken) {
136                                         threadWhoTookLock = Thread.CurrentThread.ManagedThreadId;
137                                         break;
138                                 }
139                         } while (milliSeconds == -1 || (sw.ElapsedMilliseconds - start) < milliSeconds);
140                 }
141
142                 public void Exit ()
143                 {
144                         Exit (false);
145                 }
146
147                 public void Exit (bool flushReleaseWrites)
148                 {
149                         if (isThreadOwnerTrackingEnabled && !IsHeldByCurrentThread)
150                                 throw new SynchronizationLockException ("Current thread is not the owner of this lock");
151
152                         threadWhoTookLock = int.MinValue;
153                         if (flushReleaseWrites)
154                                 Interlocked.Increment (ref ticket.Value);
155                         else
156                                 ticket.Value++;
157                 }
158         }
159
160         // Wraps a SpinLock in a reference when we need to pass
161         // around the lock
162         internal class SpinLockWrapper
163         {
164                 public SpinLock Lock = new SpinLock (false);
165         }
166 }
167 #endif