New tests.
[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                 public bool IsThreadOwnerTrackingEnabled {
53                         get {
54                                 return isThreadOwnerTrackingEnabled;
55                         }
56                 }
57
58                 public bool IsHeld {
59                         get {
60                                 // No need for barrier here
61                                 long totalValue = ticket.TotalValue;
62                                 return (totalValue >> 32) != (totalValue & 0xFFFFFFFF);
63                         }
64                 }
65
66                 public bool IsHeldByCurrentThread {
67                         get {
68                                 if (isThreadOwnerTrackingEnabled)
69                                         return IsHeld && Thread.CurrentThread.ManagedThreadId == threadWhoTookLock;
70                                 else
71                                         return IsHeld;
72                         }
73                 }
74
75                 public SpinLock (bool trackId)
76                 {
77                         this.isThreadOwnerTrackingEnabled = trackId;
78                         this.threadWhoTookLock = 0;
79                         this.ticket = new TicketType ();
80                 }
81
82                 [MonoTODO("This method is not rigorously correct. Need CER treatment")]
83                 public void Enter (ref bool lockTaken)
84                 {
85                         if (lockTaken)
86                                 throw new ArgumentException ("lockTaken", "lockTaken must be initialized to false");
87                         if (isThreadOwnerTrackingEnabled && IsHeldByCurrentThread)
88                                 throw new LockRecursionException ();
89
90                         int slot = Interlocked.Increment (ref ticket.Users) - 1;
91
92                         SpinWait wait;
93                         while (slot != ticket.Value)
94                                 wait.SpinOnce ();
95                         
96                         lockTaken = true;
97                         
98                         threadWhoTookLock = Thread.CurrentThread.ManagedThreadId;
99                 }
100
101                 [MonoTODO("This method is not rigorously correct. Need CER treatment")]
102                 public void TryEnter (ref bool lockTaken)
103                 {
104                         TryEnter (0, ref lockTaken);
105                 }
106
107                 [MonoTODO("This method is not rigorously correct. Need CER treatment")]
108                 public void TryEnter (TimeSpan timeout, ref bool lockTaken)
109                 {
110                         TryEnter ((int)timeout.TotalMilliseconds, ref lockTaken);
111                 }
112
113                 [MonoTODO("This method is not rigorously correct. Need CER treatment")]
114                 public void TryEnter (int milliSeconds, ref bool lockTaken)
115                 {
116                         if (milliSeconds < -1)
117                                 throw new ArgumentOutOfRangeException ("milliSeconds", "millisecondsTimeout is a negative number other than -1");
118                         if (lockTaken)
119                                 throw new ArgumentException ("lockTaken", "lockTaken must be initialized to false");
120                         if (isThreadOwnerTrackingEnabled && IsHeldByCurrentThread)
121                                 throw new LockRecursionException ();
122
123                         Watch sw = Watch.StartNew ();
124
125                         do {
126                                 long u = ticket.Users;
127                                 long totalValue = (u << 32) | u;
128                                 long newTotalValue
129                                         = BitConverter.IsLittleEndian ? (u << 32) | (u + 1) : ((u + 1) << 32) | u;
130                                 
131                                 lockTaken = Interlocked.CompareExchange (ref ticket.TotalValue, newTotalValue, totalValue) == totalValue;
132                                 
133                                 if (lockTaken) {
134                                         threadWhoTookLock = Thread.CurrentThread.ManagedThreadId;
135                                         break;
136                                 }
137                         } while (milliSeconds == -1 || (milliSeconds > 0 && sw.ElapsedMilliseconds < milliSeconds));
138                 }
139
140                 public void Exit ()
141                 {
142                         Exit (false);
143                 }
144
145                 public void Exit (bool flushReleaseWrites)
146                 {
147                         if (isThreadOwnerTrackingEnabled && !IsHeldByCurrentThread)
148                                 throw new SynchronizationLockException ("Current thread is not the owner of this lock");
149
150                         threadWhoTookLock = int.MinValue;
151                         if (flushReleaseWrites)
152                                 Interlocked.Increment (ref ticket.Value);
153                         else
154                                 ticket.Value++;
155                 }
156         }
157
158         // Wraps a SpinLock in a reference when we need to pass
159         // around the lock
160         internal class SpinLockWrapper
161         {
162                 public SpinLock Lock = new SpinLock (false);
163         }
164 }
165 #endif