SpinLock.cs 4.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165
  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
  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. public bool IsThreadOwnerTrackingEnabled {
  48. get {
  49. return isThreadOwnerTrackingEnabled;
  50. }
  51. }
  52. public bool IsHeld {
  53. get {
  54. // No need for barrier here
  55. long totalValue = ticket.TotalValue;
  56. return (totalValue >> 32) != (totalValue & 0xFFFFFFFF);
  57. }
  58. }
  59. public bool IsHeldByCurrentThread {
  60. get {
  61. if (isThreadOwnerTrackingEnabled)
  62. return IsHeld && Thread.CurrentThread.ManagedThreadId == threadWhoTookLock;
  63. else
  64. return IsHeld;
  65. }
  66. }
  67. public SpinLock (bool trackId)
  68. {
  69. this.isThreadOwnerTrackingEnabled = trackId;
  70. this.threadWhoTookLock = 0;
  71. this.ticket = new TicketType ();
  72. }
  73. [MonoTODO("This method is not rigorously correct. Need CER treatment")]
  74. public void Enter (ref bool lockTaken)
  75. {
  76. if (lockTaken)
  77. throw new ArgumentException ("lockTaken", "lockTaken must be initialized to false");
  78. if (isThreadOwnerTrackingEnabled && IsHeldByCurrentThread)
  79. throw new LockRecursionException ();
  80. int slot = Interlocked.Increment (ref ticket.Users) - 1;
  81. SpinWait wait;
  82. while (slot != ticket.Value)
  83. wait.SpinOnce ();
  84. lockTaken = true;
  85. threadWhoTookLock = Thread.CurrentThread.ManagedThreadId;
  86. }
  87. [MonoTODO("This method is not rigorously correct. Need CER treatment")]
  88. public void TryEnter (ref bool lockTaken)
  89. {
  90. TryEnter (0, ref lockTaken);
  91. }
  92. [MonoTODO("This method is not rigorously correct. Need CER treatment")]
  93. public void TryEnter (TimeSpan timeout, ref bool lockTaken)
  94. {
  95. TryEnter ((int)timeout.TotalMilliseconds, ref lockTaken);
  96. }
  97. [MonoTODO("This method is not rigorously correct. Need CER treatment")]
  98. public void TryEnter (int milliSeconds, ref bool lockTaken)
  99. {
  100. if (milliSeconds < -1)
  101. throw new ArgumentOutOfRangeException ("milliSeconds", "millisecondsTimeout is a negative number other than -1");
  102. if (lockTaken)
  103. throw new ArgumentException ("lockTaken", "lockTaken must be initialized to false");
  104. if (isThreadOwnerTrackingEnabled && IsHeldByCurrentThread)
  105. throw new LockRecursionException ();
  106. Watch sw = Watch.StartNew ();
  107. do {
  108. long u = ticket.Users;
  109. long totalValue = (u << 32) | u;
  110. long newTotalValue
  111. = BitConverter.IsLittleEndian ? (u << 32) | (u + 1) : ((u + 1) << 32) | u;
  112. lockTaken = Interlocked.CompareExchange (ref ticket.TotalValue, newTotalValue, totalValue) == totalValue;
  113. if (lockTaken) {
  114. threadWhoTookLock = Thread.CurrentThread.ManagedThreadId;
  115. break;
  116. }
  117. } while (milliSeconds == -1 || (milliSeconds > 0 && sw.ElapsedMilliseconds < milliSeconds));
  118. }
  119. public void Exit ()
  120. {
  121. Exit (false);
  122. }
  123. public void Exit (bool flushReleaseWrites)
  124. {
  125. if (isThreadOwnerTrackingEnabled && !IsHeldByCurrentThread)
  126. throw new SynchronizationLockException ("Current thread is not the owner of this lock");
  127. threadWhoTookLock = int.MinValue;
  128. if (flushReleaseWrites)
  129. Interlocked.Increment (ref ticket.Value);
  130. else
  131. ticket.Value++;
  132. }
  133. }
  134. // Wraps a SpinLock in a reference when we need to pass
  135. // around the lock
  136. internal class SpinLockWrapper
  137. {
  138. public SpinLock Lock = new SpinLock (false);
  139. }
  140. }
  141. #endif