SpinLock.cs 4.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180
  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. using System;
  25. using System.Runtime.ConstrainedExecution;
  26. #if NET_4_0
  27. namespace System.Threading
  28. {
  29. public struct SpinLock
  30. {
  31. const int isFree = 0;
  32. const int isOwned = 1;
  33. int lockState;
  34. readonly SpinWait sw;
  35. int threadWhoTookLock;
  36. readonly bool isThreadOwnerTrackingEnabled;
  37. public bool IsThreadOwnerTrackingEnabled {
  38. get {
  39. return isThreadOwnerTrackingEnabled;
  40. }
  41. }
  42. public bool IsHeld {
  43. get {
  44. return lockState == isOwned;
  45. }
  46. }
  47. public bool IsHeldByCurrentThread {
  48. get {
  49. if (isThreadOwnerTrackingEnabled)
  50. return lockState == isOwned && Thread.CurrentThread.ManagedThreadId == threadWhoTookLock;
  51. else
  52. return lockState == isOwned;
  53. }
  54. }
  55. public SpinLock (bool trackId)
  56. {
  57. this.isThreadOwnerTrackingEnabled = trackId;
  58. this.threadWhoTookLock = 0;
  59. this.lockState = isFree;
  60. this.sw = new SpinWait();
  61. }
  62. void CheckAndSetThreadId ()
  63. {
  64. if (threadWhoTookLock == Thread.CurrentThread.ManagedThreadId)
  65. throw new LockRecursionException("The current thread has already acquired this lock.");
  66. threadWhoTookLock = Thread.CurrentThread.ManagedThreadId;
  67. }
  68. public void Enter (ref bool lockTaken)
  69. {
  70. if (lockTaken)
  71. throw new ArgumentException ("lockTaken", "lockTaken must be initialized to false");
  72. if (isThreadOwnerTrackingEnabled && IsHeldByCurrentThread)
  73. throw new LockRecursionException ();
  74. try {
  75. Enter ();
  76. lockTaken = lockState == isOwned && Thread.CurrentThread.ManagedThreadId == threadWhoTookLock;
  77. } catch {
  78. lockTaken = false;
  79. }
  80. }
  81. internal void Enter ()
  82. {
  83. int result = Interlocked.Exchange (ref lockState, isOwned);
  84. while (result == isOwned) {
  85. sw.SpinOnce ();
  86. // Efficiently spin, until the resource looks like it might
  87. // be free. NOTE: Just reading here (as compared to repeatedly
  88. // calling Exchange) improves performance because writing
  89. // forces all CPUs to update this value
  90. result = Thread.VolatileRead (ref lockState);
  91. if (result == isFree) {
  92. result = Interlocked.Exchange (ref lockState, isOwned);
  93. if (result == isFree)
  94. break;
  95. }
  96. }
  97. CheckAndSetThreadId ();
  98. }
  99. bool TryEnter ()
  100. {
  101. // If resource available, set it to in-use and return
  102. if (Interlocked.Exchange (ref lockState, isOwned) == isFree) {
  103. CheckAndSetThreadId ();
  104. return true;
  105. }
  106. return false;
  107. }
  108. public void TryEnter (ref bool lockTaken)
  109. {
  110. TryEnter (-1, ref lockTaken);
  111. }
  112. public void TryEnter (TimeSpan timeout, ref bool lockTaken)
  113. {
  114. TryEnter ((int)timeout.TotalMilliseconds, ref lockTaken);
  115. }
  116. public void TryEnter (int milliSeconds, ref bool lockTaken)
  117. {
  118. if (milliSeconds < -1)
  119. throw new ArgumentOutOfRangeException ("milliSeconds", "millisecondsTimeout is a negative number other than -1");
  120. if (lockTaken)
  121. throw new ArgumentException ("lockTaken", "lockTaken must be initialized to false");
  122. if (isThreadOwnerTrackingEnabled && IsHeldByCurrentThread)
  123. throw new LockRecursionException ();
  124. Watch sw = Watch.StartNew ();
  125. while (milliSeconds == -1 || sw.ElapsedMilliseconds < milliSeconds) {
  126. lockTaken = TryEnter ();
  127. }
  128. sw.Stop ();
  129. }
  130. public void Exit ()
  131. {
  132. Exit (false);
  133. }
  134. public void Exit (bool flushReleaseWrites)
  135. {
  136. if (isThreadOwnerTrackingEnabled && !IsHeldByCurrentThread)
  137. throw new SynchronizationLockException ("Current thread is not the owner of this lock");
  138. threadWhoTookLock = int.MinValue;
  139. // Mark the resource as available
  140. if (!flushReleaseWrites) {
  141. lockState = isFree;
  142. } else {
  143. Interlocked.Exchange (ref lockState, isFree);
  144. }
  145. }
  146. }
  147. // Wraps a SpinLock in a reference when we need to pass
  148. // around the lock
  149. internal class SpinLockWrapper
  150. {
  151. public readonly SpinLock Lock = new SpinLock (false);
  152. }
  153. }
  154. #endif