SpinLock.cs 5.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167
  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. using System.Runtime.InteropServices;
  27. #if NET_4_0 || BOOTSTRAP_NET_4_0
  28. namespace System.Threading
  29. {
  30. [StructLayout(LayoutKind.Explicit)]
  31. internal struct TicketType {
  32. [FieldOffset(0)]
  33. public long TotalValue;
  34. [FieldOffset(0)]
  35. public int Value;
  36. [FieldOffset(4)]
  37. public int Users;
  38. }
  39. // Implement the ticket SpinLock algorithm described on http://locklessinc.com/articles/locks/
  40. // This lock is usable on both endianness
  41. // TODO: some 32 bits platform apparently doesn't support CAS with 64 bits value
  42. public struct SpinLock
  43. {
  44. TicketType ticket;
  45. int threadWhoTookLock;
  46. readonly bool isThreadOwnerTrackingEnabled;
  47. static Watch sw = Watch.StartNew ();
  48. public bool IsThreadOwnerTrackingEnabled {
  49. get {
  50. return isThreadOwnerTrackingEnabled;
  51. }
  52. }
  53. public bool IsHeld {
  54. get {
  55. // No need for barrier here
  56. long totalValue = ticket.TotalValue;
  57. return (totalValue >> 32) != (totalValue & 0xFFFFFFFF);
  58. }
  59. }
  60. public bool IsHeldByCurrentThread {
  61. get {
  62. if (isThreadOwnerTrackingEnabled)
  63. return IsHeld && Thread.CurrentThread.ManagedThreadId == threadWhoTookLock;
  64. else
  65. return IsHeld;
  66. }
  67. }
  68. public SpinLock (bool trackId)
  69. {
  70. this.isThreadOwnerTrackingEnabled = trackId;
  71. this.threadWhoTookLock = 0;
  72. this.ticket = new TicketType ();
  73. }
  74. [MonoTODO("This method is not rigorously correct. Need CER treatment")]
  75. public void Enter (ref bool lockTaken)
  76. {
  77. if (lockTaken)
  78. throw new ArgumentException ("lockTaken", "lockTaken must be initialized to false");
  79. if (isThreadOwnerTrackingEnabled && IsHeldByCurrentThread)
  80. throw new LockRecursionException ();
  81. int slot = Interlocked.Increment (ref ticket.Users) - 1;
  82. SpinWait wait = new SpinWait ();
  83. while (slot != ticket.Value)
  84. wait.SpinOnce ();
  85. lockTaken = true;
  86. threadWhoTookLock = Thread.CurrentThread.ManagedThreadId;
  87. }
  88. [MonoTODO("This method is not rigorously correct. Need CER treatment")]
  89. public void TryEnter (ref bool lockTaken)
  90. {
  91. TryEnter (0, ref lockTaken);
  92. }
  93. [MonoTODO("This method is not rigorously correct. Need CER treatment")]
  94. public void TryEnter (TimeSpan timeout, ref bool lockTaken)
  95. {
  96. TryEnter ((int)timeout.TotalMilliseconds, ref lockTaken);
  97. }
  98. [MonoTODO("This method is not rigorously correct. Need CER treatment")]
  99. public void TryEnter (int milliSeconds, ref bool lockTaken)
  100. {
  101. if (milliSeconds < -1)
  102. throw new ArgumentOutOfRangeException ("milliSeconds", "millisecondsTimeout is a negative number other than -1");
  103. if (lockTaken)
  104. throw new ArgumentException ("lockTaken", "lockTaken must be initialized to false");
  105. if (isThreadOwnerTrackingEnabled && IsHeldByCurrentThread)
  106. throw new LockRecursionException ();
  107. long start = milliSeconds == -1 ? 0 : sw.ElapsedMilliseconds;
  108. do {
  109. long u = ticket.Users;
  110. long totalValue = (u << 32) | u;
  111. long newTotalValue
  112. = BitConverter.IsLittleEndian ? (u << 32) | (u + 1) : ((u + 1) << 32) | u;
  113. lockTaken = Interlocked.CompareExchange (ref ticket.TotalValue, newTotalValue, totalValue) == totalValue;
  114. if (lockTaken) {
  115. threadWhoTookLock = Thread.CurrentThread.ManagedThreadId;
  116. break;
  117. }
  118. } while (milliSeconds == -1 || (sw.ElapsedMilliseconds - start) < milliSeconds);
  119. }
  120. public void Exit ()
  121. {
  122. Exit (false);
  123. }
  124. public void Exit (bool flushReleaseWrites)
  125. {
  126. if (isThreadOwnerTrackingEnabled && !IsHeldByCurrentThread)
  127. throw new SynchronizationLockException ("Current thread is not the owner of this lock");
  128. threadWhoTookLock = int.MinValue;
  129. if (flushReleaseWrites)
  130. Interlocked.Increment (ref ticket.Value);
  131. else
  132. ticket.Value++;
  133. }
  134. }
  135. // Wraps a SpinLock in a reference when we need to pass
  136. // around the lock
  137. internal class SpinLockWrapper
  138. {
  139. public SpinLock Lock = new SpinLock (false);
  140. }
  141. }
  142. #endif