SpinLock.cs 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199
  1. // SpinLock.cs
  2. //
  3. // Copyright (c) 2008 Jérémie "Garuma" Laval
  4. // Copyright 2011 Xamarin Inc (http://www.xamarin.com).
  5. //
  6. // Permission is hereby granted, free of charge, to any person obtaining a copy
  7. // of this software and associated documentation files (the "Software"), to deal
  8. // in the Software without restriction, including without limitation the rights
  9. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  10. // copies of the Software, and to permit persons to whom the Software is
  11. // furnished to do so, subject to the following conditions:
  12. //
  13. // The above copyright notice and this permission notice shall be included in
  14. // all copies or substantial portions of the Software.
  15. //
  16. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  17. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  18. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  19. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  20. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  21. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  22. // THE SOFTWARE.
  23. //
  24. //
  25. #if NET_4_0 || MOBILE
  26. using System;
  27. using System.Collections.Concurrent;
  28. using System.Runtime.ConstrainedExecution;
  29. using System.Runtime.InteropServices;
  30. using System.Runtime.CompilerServices;
  31. namespace System.Threading
  32. {
  33. [StructLayout(LayoutKind.Explicit)]
  34. internal struct TicketType {
  35. [FieldOffset(0)]
  36. public long TotalValue;
  37. [FieldOffset(0)]
  38. public int Value;
  39. [FieldOffset(4)]
  40. public int Users;
  41. }
  42. /* Implement the ticket SpinLock algorithm described on http://locklessinc.com/articles/locks/
  43. * This lock is usable on both endianness.
  44. * All the try/finally patterns in this class and various extra gimmicks compared to the original
  45. * algorithm are here to avoid problems caused by asynchronous exceptions.
  46. */
  47. [System.Diagnostics.DebuggerDisplay ("IsHeld = {IsHeld}")]
  48. [System.Diagnostics.DebuggerTypeProxy ("System.Threading.SpinLock+SystemThreading_SpinLockDebugView")]
  49. public struct SpinLock
  50. {
  51. TicketType ticket;
  52. int threadWhoTookLock;
  53. readonly bool isThreadOwnerTrackingEnabled;
  54. static readonly Watch sw = Watch.StartNew ();
  55. ConcurrentOrderedList<int> stallTickets;
  56. public bool IsThreadOwnerTrackingEnabled {
  57. get {
  58. return isThreadOwnerTrackingEnabled;
  59. }
  60. }
  61. public bool IsHeld {
  62. get {
  63. // No need for barrier here
  64. long totalValue = ticket.TotalValue;
  65. return (totalValue >> 32) != (totalValue & 0xFFFFFFFF);
  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. public SpinLock (bool enableThreadOwnerTracking)
  77. {
  78. this.isThreadOwnerTrackingEnabled = enableThreadOwnerTracking;
  79. this.threadWhoTookLock = 0;
  80. this.ticket = new TicketType ();
  81. this.stallTickets = null;
  82. }
  83. [MonoTODO ("Not safe against async exceptions")]
  84. public void Enter (ref bool lockTaken)
  85. {
  86. if (lockTaken)
  87. throw new ArgumentException ("lockTaken", "lockTaken must be initialized to false");
  88. if (isThreadOwnerTrackingEnabled && IsHeldByCurrentThread)
  89. throw new LockRecursionException ();
  90. int slot = -1;
  91. RuntimeHelpers.PrepareConstrainedRegions ();
  92. try {
  93. slot = Interlocked.Increment (ref ticket.Users) - 1;
  94. SpinWait wait = new SpinWait ();
  95. while (slot != ticket.Value) {
  96. wait.SpinOnce ();
  97. while (stallTickets != null && stallTickets.TryRemove (ticket.Value))
  98. ++ticket.Value;
  99. }
  100. } finally {
  101. if (slot == ticket.Value) {
  102. lockTaken = true;
  103. threadWhoTookLock = Thread.CurrentThread.ManagedThreadId;
  104. } else if (slot != -1) {
  105. // We have been interrupted, initialize stallTickets
  106. if (stallTickets == null)
  107. Interlocked.CompareExchange (ref stallTickets, new ConcurrentOrderedList<int> (), null);
  108. stallTickets.TryAdd (slot);
  109. }
  110. }
  111. }
  112. public void TryEnter (ref bool lockTaken)
  113. {
  114. TryEnter (0, ref lockTaken);
  115. }
  116. public void TryEnter (TimeSpan timeout, ref bool lockTaken)
  117. {
  118. TryEnter ((int)timeout.TotalMilliseconds, ref lockTaken);
  119. }
  120. public void TryEnter (int millisecondsTimeout, ref bool lockTaken)
  121. {
  122. if (millisecondsTimeout < -1)
  123. throw new ArgumentOutOfRangeException ("milliSeconds", "millisecondsTimeout is a negative number other than -1");
  124. if (lockTaken)
  125. throw new ArgumentException ("lockTaken", "lockTaken must be initialized to false");
  126. if (isThreadOwnerTrackingEnabled && IsHeldByCurrentThread)
  127. throw new LockRecursionException ();
  128. long start = millisecondsTimeout == -1 ? 0 : sw.ElapsedMilliseconds;
  129. bool stop = false;
  130. do {
  131. while (stallTickets != null && stallTickets.TryRemove (ticket.Value))
  132. ++ticket.Value;
  133. long u = ticket.Users;
  134. long totalValue = (u << 32) | u;
  135. long newTotalValue
  136. = BitConverter.IsLittleEndian ? (u << 32) | (u + 1) : ((u + 1) << 32) | u;
  137. RuntimeHelpers.PrepareConstrainedRegions ();
  138. try {}
  139. finally {
  140. lockTaken = Interlocked.CompareExchange (ref ticket.TotalValue, newTotalValue, totalValue) == totalValue;
  141. if (lockTaken) {
  142. threadWhoTookLock = Thread.CurrentThread.ManagedThreadId;
  143. stop = true;
  144. }
  145. }
  146. } while (!stop && (millisecondsTimeout == -1 || (sw.ElapsedMilliseconds - start) < millisecondsTimeout));
  147. }
  148. [ReliabilityContract (Consistency.WillNotCorruptState, Cer.Success)]
  149. public void Exit ()
  150. {
  151. Exit (false);
  152. }
  153. [ReliabilityContract (Consistency.WillNotCorruptState, Cer.Success)]
  154. public void Exit (bool useMemoryBarrier)
  155. {
  156. RuntimeHelpers.PrepareConstrainedRegions ();
  157. try {}
  158. finally {
  159. if (isThreadOwnerTrackingEnabled && !IsHeldByCurrentThread)
  160. throw new SynchronizationLockException ("Current thread is not the owner of this lock");
  161. threadWhoTookLock = int.MinValue;
  162. do {
  163. if (useMemoryBarrier)
  164. Interlocked.Increment (ref ticket.Value);
  165. else
  166. ticket.Value++;
  167. } while (stallTickets != null && stallTickets.TryRemove (ticket.Value));
  168. }
  169. }
  170. }
  171. }
  172. #endif