SpinLock.cs 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204
  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. #if NET_4_0
  25. using System;
  26. using System.Collections.Concurrent;
  27. using System.Runtime.ConstrainedExecution;
  28. using System.Runtime.InteropServices;
  29. using System.Runtime.CompilerServices;
  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. /* Implement the ticket SpinLock algorithm described on http://locklessinc.com/articles/locks/
  42. * This lock is usable on both endianness.
  43. * All the try/finally patterns in this class and various extra gimmicks compared to the original
  44. * algorithm are here to avoid problems caused by asynchronous exceptions.
  45. */
  46. [System.Diagnostics.DebuggerDisplay ("IsHeld = {IsHeld}")]
  47. [System.Diagnostics.DebuggerTypeProxy ("System.Threading.SpinLock+SystemThreading_SpinLockDebugView")]
  48. public struct SpinLock
  49. {
  50. TicketType ticket;
  51. int threadWhoTookLock;
  52. readonly bool isThreadOwnerTrackingEnabled;
  53. static Watch sw = Watch.StartNew ();
  54. ConcurrentOrderedList<int> stallTickets;
  55. public bool IsThreadOwnerTrackingEnabled {
  56. get {
  57. return isThreadOwnerTrackingEnabled;
  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. public bool IsHeldByCurrentThread {
  68. get {
  69. if (isThreadOwnerTrackingEnabled)
  70. return IsHeld && Thread.CurrentThread.ManagedThreadId == threadWhoTookLock;
  71. else
  72. return IsHeld;
  73. }
  74. }
  75. public SpinLock (bool enableThreadOwnerTracking)
  76. {
  77. this.isThreadOwnerTrackingEnabled = enableThreadOwnerTracking;
  78. this.threadWhoTookLock = 0;
  79. this.ticket = new TicketType ();
  80. this.stallTickets = null;
  81. }
  82. [MonoTODO ("Not safe against async exceptions")]
  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. int slot = -1;
  90. RuntimeHelpers.PrepareConstrainedRegions ();
  91. try {
  92. slot = Interlocked.Increment (ref ticket.Users) - 1;
  93. SpinWait wait = new SpinWait ();
  94. while (slot != ticket.Value) {
  95. wait.SpinOnce ();
  96. while (stallTickets != null && stallTickets.TryRemove (ticket.Value))
  97. ++ticket.Value;
  98. }
  99. } finally {
  100. if (slot == ticket.Value) {
  101. lockTaken = true;
  102. threadWhoTookLock = Thread.CurrentThread.ManagedThreadId;
  103. } else if (slot != -1) {
  104. // We have been interrupted, initialize stallTickets
  105. if (stallTickets == null)
  106. Interlocked.CompareExchange (ref stallTickets, new ConcurrentOrderedList<int> (), null);
  107. stallTickets.TryAdd (slot);
  108. }
  109. }
  110. }
  111. public void TryEnter (ref bool lockTaken)
  112. {
  113. TryEnter (0, ref lockTaken);
  114. }
  115. public void TryEnter (TimeSpan timeout, ref bool lockTaken)
  116. {
  117. TryEnter ((int)timeout.TotalMilliseconds, ref lockTaken);
  118. }
  119. public void TryEnter (int millisecondsTimeout, ref bool lockTaken)
  120. {
  121. if (millisecondsTimeout < -1)
  122. throw new ArgumentOutOfRangeException ("milliSeconds", "millisecondsTimeout is a negative number other than -1");
  123. if (lockTaken)
  124. throw new ArgumentException ("lockTaken", "lockTaken must be initialized to false");
  125. if (isThreadOwnerTrackingEnabled && IsHeldByCurrentThread)
  126. throw new LockRecursionException ();
  127. long start = millisecondsTimeout == -1 ? 0 : sw.ElapsedMilliseconds;
  128. bool stop = false;
  129. do {
  130. while (stallTickets != null && stallTickets.TryRemove (ticket.Value))
  131. ++ticket.Value;
  132. long u = ticket.Users;
  133. long totalValue = (u << 32) | u;
  134. long newTotalValue
  135. = BitConverter.IsLittleEndian ? (u << 32) | (u + 1) : ((u + 1) << 32) | u;
  136. RuntimeHelpers.PrepareConstrainedRegions ();
  137. try {}
  138. finally {
  139. lockTaken = Interlocked.CompareExchange (ref ticket.TotalValue, newTotalValue, totalValue) == totalValue;
  140. if (lockTaken) {
  141. threadWhoTookLock = Thread.CurrentThread.ManagedThreadId;
  142. stop = true;
  143. }
  144. }
  145. } while (!stop && (millisecondsTimeout == -1 || (sw.ElapsedMilliseconds - start) < millisecondsTimeout));
  146. }
  147. public void Exit ()
  148. {
  149. Exit (false);
  150. }
  151. [ReliabilityContract (Consistency.WillNotCorruptState, Cer.Success)]
  152. public void Exit (bool useMemoryBarrier)
  153. {
  154. RuntimeHelpers.PrepareConstrainedRegions ();
  155. try {}
  156. finally {
  157. if (isThreadOwnerTrackingEnabled && !IsHeldByCurrentThread)
  158. throw new SynchronizationLockException ("Current thread is not the owner of this lock");
  159. threadWhoTookLock = int.MinValue;
  160. do {
  161. if (useMemoryBarrier)
  162. Interlocked.Increment (ref ticket.Value);
  163. else
  164. ticket.Value++;
  165. } while (stallTickets != null && stallTickets.TryRemove (ticket.Value));
  166. }
  167. }
  168. }
  169. // Wraps a SpinLock in a reference when we need to pass
  170. // around the lock
  171. internal class SpinLockWrapper
  172. {
  173. public SpinLock Lock = new SpinLock (false);
  174. }
  175. }
  176. #endif