3 // Copyright (c) 2008 Jérémie "Garuma" Laval
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:
12 // The above copyright notice and this permission notice shall be included in
13 // all copies or substantial portions of the Software.
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
26 using System.Runtime.ConstrainedExecution;
27 using System.Runtime.InteropServices;
29 #if NET_4_0 || BOOTSTRAP_NET_4_0
30 namespace System.Threading
32 [StructLayout(LayoutKind.Explicit)]
33 internal struct TicketType {
35 public long TotalValue;
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
49 int threadWhoTookLock;
50 readonly bool isThreadOwnerTrackingEnabled;
52 public bool IsThreadOwnerTrackingEnabled {
54 return isThreadOwnerTrackingEnabled;
60 // No need for barrier here
61 long totalValue = ticket.TotalValue;
62 return (totalValue >> 32) != (totalValue & 0xFFFFFFFF);
66 public bool IsHeldByCurrentThread {
68 if (isThreadOwnerTrackingEnabled)
69 return IsHeld && Thread.CurrentThread.ManagedThreadId == threadWhoTookLock;
75 public SpinLock (bool trackId)
77 this.isThreadOwnerTrackingEnabled = trackId;
78 this.threadWhoTookLock = 0;
79 this.ticket = new TicketType ();
82 [MonoTODO("This method is not rigorously correct. Need CER treatment")]
83 public void Enter (ref bool lockTaken)
86 throw new ArgumentException ("lockTaken", "lockTaken must be initialized to false");
87 if (isThreadOwnerTrackingEnabled && IsHeldByCurrentThread)
88 throw new LockRecursionException ();
90 int slot = Interlocked.Increment (ref ticket.Users) - 1;
93 while (slot != ticket.Value)
98 threadWhoTookLock = Thread.CurrentThread.ManagedThreadId;
101 [MonoTODO("This method is not rigorously correct. Need CER treatment")]
102 public void TryEnter (ref bool lockTaken)
104 TryEnter (0, ref lockTaken);
107 [MonoTODO("This method is not rigorously correct. Need CER treatment")]
108 public void TryEnter (TimeSpan timeout, ref bool lockTaken)
110 TryEnter ((int)timeout.TotalMilliseconds, ref lockTaken);
113 [MonoTODO("This method is not rigorously correct. Need CER treatment")]
114 public void TryEnter (int milliSeconds, ref bool lockTaken)
116 if (milliSeconds < -1)
117 throw new ArgumentOutOfRangeException ("milliSeconds", "millisecondsTimeout is a negative number other than -1");
119 throw new ArgumentException ("lockTaken", "lockTaken must be initialized to false");
120 if (isThreadOwnerTrackingEnabled && IsHeldByCurrentThread)
121 throw new LockRecursionException ();
123 Watch sw = Watch.StartNew ();
126 long u = ticket.Users;
127 long totalValue = (u << 32) | u;
129 = BitConverter.IsLittleEndian ? (u << 32) | (u + 1) : ((u + 1) << 32) | u;
131 lockTaken = Interlocked.CompareExchange (ref ticket.TotalValue, newTotalValue, totalValue) == totalValue;
134 threadWhoTookLock = Thread.CurrentThread.ManagedThreadId;
137 } while (milliSeconds == -1 || (milliSeconds > 0 && sw.ElapsedMilliseconds < milliSeconds));
145 public void Exit (bool flushReleaseWrites)
147 if (isThreadOwnerTrackingEnabled && !IsHeldByCurrentThread)
148 throw new SynchronizationLockException ("Current thread is not the owner of this lock");
150 threadWhoTookLock = int.MinValue;
151 if (flushReleaseWrites)
152 Interlocked.Increment (ref ticket.Value);
158 // Wraps a SpinLock in a reference when we need to pass
160 internal class SpinLockWrapper
162 public SpinLock Lock = new SpinLock (false);