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 static Watch sw = Watch.StartNew ();
54 public bool IsThreadOwnerTrackingEnabled {
56 return isThreadOwnerTrackingEnabled;
62 // No need for barrier here
63 long totalValue = ticket.TotalValue;
64 return (totalValue >> 32) != (totalValue & 0xFFFFFFFF);
68 public bool IsHeldByCurrentThread {
70 if (isThreadOwnerTrackingEnabled)
71 return IsHeld && Thread.CurrentThread.ManagedThreadId == threadWhoTookLock;
77 public SpinLock (bool trackId)
79 this.isThreadOwnerTrackingEnabled = trackId;
80 this.threadWhoTookLock = 0;
81 this.ticket = new TicketType ();
84 [MonoTODO("This method is not rigorously correct. Need CER treatment")]
85 public void Enter (ref bool lockTaken)
88 throw new ArgumentException ("lockTaken", "lockTaken must be initialized to false");
89 if (isThreadOwnerTrackingEnabled && IsHeldByCurrentThread)
90 throw new LockRecursionException ();
92 int slot = Interlocked.Increment (ref ticket.Users) - 1;
94 SpinWait wait = new SpinWait ();
95 while (slot != ticket.Value)
100 threadWhoTookLock = Thread.CurrentThread.ManagedThreadId;
103 [MonoTODO("This method is not rigorously correct. Need CER treatment")]
104 public void TryEnter (ref bool lockTaken)
106 TryEnter (0, ref lockTaken);
109 [MonoTODO("This method is not rigorously correct. Need CER treatment")]
110 public void TryEnter (TimeSpan timeout, ref bool lockTaken)
112 TryEnter ((int)timeout.TotalMilliseconds, ref lockTaken);
115 [MonoTODO("This method is not rigorously correct. Need CER treatment")]
116 public void TryEnter (int milliSeconds, ref bool lockTaken)
118 if (milliSeconds < -1)
119 throw new ArgumentOutOfRangeException ("milliSeconds", "millisecondsTimeout is a negative number other than -1");
121 throw new ArgumentException ("lockTaken", "lockTaken must be initialized to false");
122 if (isThreadOwnerTrackingEnabled && IsHeldByCurrentThread)
123 throw new LockRecursionException ();
125 long start = milliSeconds == -1 ? 0 : sw.ElapsedMilliseconds;
128 long u = ticket.Users;
129 long totalValue = (u << 32) | u;
131 = BitConverter.IsLittleEndian ? (u << 32) | (u + 1) : ((u + 1) << 32) | u;
133 lockTaken = Interlocked.CompareExchange (ref ticket.TotalValue, newTotalValue, totalValue) == totalValue;
136 threadWhoTookLock = Thread.CurrentThread.ManagedThreadId;
139 } while (milliSeconds == -1 || (sw.ElapsedMilliseconds - start) < milliSeconds);
147 public void Exit (bool flushReleaseWrites)
149 if (isThreadOwnerTrackingEnabled && !IsHeldByCurrentThread)
150 throw new SynchronizationLockException ("Current thread is not the owner of this lock");
152 threadWhoTookLock = int.MinValue;
153 if (flushReleaseWrites)
154 Interlocked.Increment (ref ticket.Value);
160 // Wraps a SpinLock in a reference when we need to pass
162 internal class SpinLockWrapper
164 public SpinLock Lock = new SpinLock (false);