ReaderWriterLockSlim.cs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403
  1. //
  2. // System.Threading.ReaderWriterLockSlim.cs
  3. //
  4. // Author:
  5. // Jérémie "Garuma" Laval <[email protected]>
  6. //
  7. // Copyright (c) 2010 Jérémie "Garuma" Laval
  8. //
  9. // Permission is hereby granted, free of charge, to any person obtaining
  10. // a copy of this software and associated documentation files (the
  11. // "Software"), to deal in the Software without restriction, including
  12. // without limitation the rights to use, copy, modify, merge, publish,
  13. // distribute, sublicense, and/or sell copies of the Software, and to
  14. // permit persons to whom the Software is furnished to do so, subject to
  15. // the following conditions:
  16. //
  17. // The above copyright notice and this permission notice shall be
  18. // included in all copies or substantial portions of the Software.
  19. //
  20. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  21. // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  22. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  23. // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
  24. // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
  25. // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
  26. // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  27. //
  28. using System;
  29. using System.Collections;
  30. using System.Collections.Generic;
  31. using System.Security.Permissions;
  32. using System.Diagnostics;
  33. using System.Threading;
  34. namespace System.Threading {
  35. [Flags]
  36. internal enum ThreadLockState
  37. {
  38. None = 0,
  39. Read = 1,
  40. Write = 2,
  41. Upgradable = 4,
  42. UpgradedRead = 5,
  43. UpgradedWrite = 6
  44. }
  45. internal static class ThreadLockStateExtensions
  46. {
  47. internal static bool Has (this ThreadLockState state, ThreadLockState value)
  48. {
  49. return (state & value) > 0;
  50. }
  51. }
  52. [HostProtectionAttribute(SecurityAction.LinkDemand, MayLeakOnAbort = true)]
  53. [HostProtectionAttribute(SecurityAction.LinkDemand, Synchronization = true, ExternalThreading = true)]
  54. public class ReaderWriterLockSlim : IDisposable
  55. {
  56. /* Position of each bit isn't really important
  57. * but their relative order is
  58. */
  59. const int RwWaitBit = 0;
  60. const int RwWaitUpgradeBit = 1;
  61. const int RwWriteBit = 2;
  62. const int RwReadBit = 3;
  63. const int RwWait = 1;
  64. const int RwWaitUpgrade = 2;
  65. const int RwWrite = 4;
  66. const int RwRead = 8;
  67. int rwlock;
  68. readonly LockRecursionPolicy recursionPolicy;
  69. AtomicBoolean upgradableTaken = new AtomicBoolean ();
  70. ManualResetEventSlim upgradableEvent = new ManualResetEventSlim (true);
  71. int numReadWaiters, numUpgradeWaiters, numWriteWaiters;
  72. bool disposed;
  73. [ThreadStatic]
  74. static IDictionary<ReaderWriterLockSlim, ThreadLockState> currentThreadState;
  75. public ReaderWriterLockSlim () : this (LockRecursionPolicy.NoRecursion)
  76. {
  77. }
  78. public ReaderWriterLockSlim (LockRecursionPolicy recursionPolicy)
  79. {
  80. if (recursionPolicy != LockRecursionPolicy.NoRecursion)
  81. throw new NotSupportedException ("Creating a recursion-aware reader-writer lock is not yet supported");
  82. this.recursionPolicy = recursionPolicy;
  83. }
  84. public void EnterReadLock ()
  85. {
  86. TryEnterReadLock (-1);
  87. }
  88. public bool TryEnterReadLock (int millisecondsTimeout)
  89. {
  90. if (CheckState (millisecondsTimeout, ThreadLockState.Read))
  91. return true;
  92. // This is downgrading from upgradable, no need for check since
  93. // we already have a sort-of read lock that's going to disappear
  94. // after user calls ExitUpgradeableReadLock
  95. if (CurrentThreadState.Has (ThreadLockState.Upgradable)) {
  96. Interlocked.Add (ref rwlock, RwRead);
  97. CurrentThreadState = CurrentThreadState ^ ThreadLockState.Read;
  98. return true;
  99. }
  100. Stopwatch sw = Stopwatch.StartNew ();
  101. Interlocked.Increment (ref numReadWaiters);
  102. while (millisecondsTimeout == -1 || sw.ElapsedMilliseconds < millisecondsTimeout) {
  103. if ((rwlock & 0x7) > 0) {
  104. Thread.Sleep (1);
  105. continue;
  106. }
  107. if ((Interlocked.Add (ref rwlock, RwRead) & 0x7) == 0) {
  108. CurrentThreadState = CurrentThreadState ^ ThreadLockState.Read;
  109. Interlocked.Decrement (ref numReadWaiters);
  110. return true;
  111. }
  112. Interlocked.Add (ref rwlock, -RwRead);
  113. Thread.Sleep (1);
  114. }
  115. Interlocked.Decrement (ref numReadWaiters);
  116. return false;
  117. }
  118. public bool TryEnterReadLock (TimeSpan timeout)
  119. {
  120. return TryEnterReadLock (CheckTimeout (timeout));
  121. }
  122. public void ExitReadLock ()
  123. {
  124. if (CurrentThreadState != ThreadLockState.Read)
  125. throw new SynchronizationLockException ("The current thread has not entered the lock in read mode");
  126. CurrentThreadState = ThreadLockState.None;
  127. Interlocked.Add (ref rwlock, -RwRead);
  128. }
  129. public void EnterWriteLock ()
  130. {
  131. TryEnterWriteLock (-1);
  132. }
  133. public bool TryEnterWriteLock (int millisecondsTimeout)
  134. {
  135. bool isUpgradable = CurrentThreadState.Has (ThreadLockState.Upgradable);
  136. if (CheckState (millisecondsTimeout, isUpgradable ? ThreadLockState.UpgradedWrite : ThreadLockState.Write))
  137. return true;
  138. Stopwatch sw = Stopwatch.StartNew ();
  139. Interlocked.Increment (ref numWriteWaiters);
  140. // If the code goes there that means we had a read lock beforehand
  141. if (isUpgradable && rwlock >= RwRead)
  142. Interlocked.Add (ref rwlock, -RwRead);
  143. int stateCheck = isUpgradable ? RwWaitUpgrade : RwWait;
  144. int appendValue = RwWait | (isUpgradable ? RwWaitUpgrade : 0);
  145. while (millisecondsTimeout < 0 || sw.ElapsedMilliseconds < millisecondsTimeout) {
  146. int state = rwlock;
  147. if (state <= stateCheck) {
  148. if (Interlocked.CompareExchange (ref rwlock, RwWrite, state) == state) {
  149. CurrentThreadState = isUpgradable ? ThreadLockState.UpgradedWrite : ThreadLockState.Write;
  150. Interlocked.Decrement (ref numWriteWaiters);
  151. return true;
  152. }
  153. state = rwlock;
  154. }
  155. while ((state & RwWait) == 0 && Interlocked.CompareExchange (ref rwlock, state | appendValue, state) == state)
  156. state = rwlock;
  157. while (rwlock > stateCheck && (millisecondsTimeout < 0 || sw.ElapsedMilliseconds < millisecondsTimeout))
  158. Thread.Sleep (1);
  159. }
  160. Interlocked.Decrement (ref numWriteWaiters);
  161. return false;
  162. }
  163. public bool TryEnterWriteLock (TimeSpan timeout)
  164. {
  165. return TryEnterWriteLock (CheckTimeout (timeout));
  166. }
  167. public void ExitWriteLock ()
  168. {
  169. if (!CurrentThreadState.Has (ThreadLockState.Write))
  170. throw new SynchronizationLockException ("The current thread has not entered the lock in write mode");
  171. CurrentThreadState = CurrentThreadState ^ ThreadLockState.Write;
  172. Interlocked.Add (ref rwlock, -RwWrite);
  173. }
  174. public void EnterUpgradeableReadLock ()
  175. {
  176. TryEnterUpgradeableReadLock (-1);
  177. }
  178. //
  179. // Taking the Upgradable read lock is like taking a read lock
  180. // but we limit it to a single upgradable at a time.
  181. //
  182. public bool TryEnterUpgradeableReadLock (int millisecondsTimeout)
  183. {
  184. if (CheckState (millisecondsTimeout, ThreadLockState.Upgradable))
  185. return true;
  186. if (CurrentThreadState.Has (ThreadLockState.Read))
  187. throw new LockRecursionException ("The current thread has already entered read mode");
  188. Stopwatch sw = Stopwatch.StartNew ();
  189. Interlocked.Increment (ref numUpgradeWaiters);
  190. while (!upgradableEvent.IsSet || !upgradableTaken.TryRelaxedSet ()) {
  191. if (millisecondsTimeout != -1 && sw.ElapsedMilliseconds > millisecondsTimeout) {
  192. Interlocked.Decrement (ref numUpgradeWaiters);
  193. return false;
  194. }
  195. upgradableEvent.Wait (ComputeTimeout (millisecondsTimeout, sw));
  196. }
  197. upgradableEvent.Reset ();
  198. if (TryEnterReadLock (ComputeTimeout (millisecondsTimeout, sw))) {
  199. CurrentThreadState = ThreadLockState.Upgradable;
  200. Interlocked.Decrement (ref numUpgradeWaiters);
  201. return true;
  202. }
  203. upgradableTaken.Value = false;
  204. upgradableEvent.Set ();
  205. Interlocked.Decrement (ref numUpgradeWaiters);
  206. return false;
  207. }
  208. public bool TryEnterUpgradeableReadLock (TimeSpan timeout)
  209. {
  210. return TryEnterUpgradeableReadLock (CheckTimeout (timeout));
  211. }
  212. public void ExitUpgradeableReadLock ()
  213. {
  214. if (!CurrentThreadState.Has (ThreadLockState.Upgradable | ThreadLockState.Read))
  215. throw new SynchronizationLockException ("The current thread has not entered the lock in upgradable mode");
  216. upgradableTaken.Value = false;
  217. upgradableEvent.Set ();
  218. CurrentThreadState = CurrentThreadState ^ ThreadLockState.Upgradable;
  219. Interlocked.Add (ref rwlock, -RwRead);
  220. }
  221. public void Dispose ()
  222. {
  223. disposed = true;
  224. }
  225. public bool IsReadLockHeld {
  226. get {
  227. return rwlock >= RwRead;
  228. }
  229. }
  230. public bool IsWriteLockHeld {
  231. get {
  232. return (rwlock & RwWrite) > 0;
  233. }
  234. }
  235. public bool IsUpgradeableReadLockHeld {
  236. get {
  237. return upgradableTaken.Value;
  238. }
  239. }
  240. public int CurrentReadCount {
  241. get {
  242. return (rwlock >> RwReadBit) - (IsUpgradeableReadLockHeld ? 1 : 0);
  243. }
  244. }
  245. public int RecursiveReadCount {
  246. get {
  247. return IsReadLockHeld ? IsUpgradeableReadLockHeld ? 0 : 1 : 0;
  248. }
  249. }
  250. public int RecursiveUpgradeCount {
  251. get {
  252. return IsUpgradeableReadLockHeld ? 1 : 0;
  253. }
  254. }
  255. public int RecursiveWriteCount {
  256. get {
  257. return IsWriteLockHeld ? 1 : 0;
  258. }
  259. }
  260. public int WaitingReadCount {
  261. get {
  262. return numReadWaiters;
  263. }
  264. }
  265. public int WaitingUpgradeCount {
  266. get {
  267. return numUpgradeWaiters;
  268. }
  269. }
  270. public int WaitingWriteCount {
  271. get {
  272. return numWriteWaiters;
  273. }
  274. }
  275. public LockRecursionPolicy RecursionPolicy {
  276. get {
  277. return recursionPolicy;
  278. }
  279. }
  280. ThreadLockState CurrentThreadState {
  281. get {
  282. // TODO: provide a IEqualityComparer thingie to have better hashes
  283. if (currentThreadState == null)
  284. currentThreadState = new Dictionary<ReaderWriterLockSlim, ThreadLockState> ();
  285. ThreadLockState state;
  286. if (!currentThreadState.TryGetValue (this, out state))
  287. currentThreadState[this] = state = ThreadLockState.None;
  288. return state;
  289. }
  290. set {
  291. if (currentThreadState == null)
  292. currentThreadState = new Dictionary<ReaderWriterLockSlim, ThreadLockState> ();
  293. currentThreadState[this] = value;
  294. }
  295. }
  296. bool CheckState (int millisecondsTimeout, ThreadLockState validState)
  297. {
  298. if (disposed)
  299. throw new ObjectDisposedException ("ReaderWriterLockSlim");
  300. if (millisecondsTimeout < Timeout.Infinite)
  301. throw new ArgumentOutOfRangeException ("millisecondsTimeout");
  302. // Detect and prevent recursion
  303. ThreadLockState ctstate = CurrentThreadState;
  304. if (recursionPolicy == LockRecursionPolicy.NoRecursion)
  305. if ((ctstate != ThreadLockState.None && ctstate != ThreadLockState.Upgradable)
  306. || (ctstate == ThreadLockState.Upgradable && validState == ThreadLockState.Upgradable))
  307. throw new LockRecursionException ("The current thread has already a lock and recursion isn't supported");
  308. // If we already had lock, just return
  309. if (CurrentThreadState == validState)
  310. return true;
  311. return false;
  312. }
  313. static int CheckTimeout (TimeSpan timeout)
  314. {
  315. try {
  316. return checked ((int)timeout.TotalMilliseconds);
  317. } catch (System.OverflowException) {
  318. throw new ArgumentOutOfRangeException ("timeout");
  319. }
  320. }
  321. static int ComputeTimeout (int millisecondsTimeout, Stopwatch sw)
  322. {
  323. return millisecondsTimeout == -1 ? -1 : (int)Math.Max (sw.ElapsedMilliseconds - millisecondsTimeout, 1);
  324. }
  325. }
  326. }