ReaderWriterLockSlim.cs 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484
  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. [HostProtectionAttribute(SecurityAction.LinkDemand, MayLeakOnAbort = true)]
  36. [HostProtectionAttribute(SecurityAction.LinkDemand, Synchronization = true, ExternalThreading = true)]
  37. public class ReaderWriterLockSlim : IDisposable
  38. {
  39. /* Position of each bit isn't really important
  40. * but their relative order is
  41. */
  42. const int RwReadBit = 3;
  43. /* These values are used to manipulate the corresponding flags in rwlock field
  44. */
  45. const int RwWait = 1;
  46. const int RwWaitUpgrade = 2;
  47. const int RwWrite = 4;
  48. const int RwRead = 8;
  49. /* Some explanations: this field is the central point of the lock and keep track of all the requests
  50. * that are being made. The 3 lowest bits are used as flag to track "destructive" lock entries
  51. * (i.e attempting to take the write lock with or without having acquired an upgradeable lock beforehand).
  52. * All the remaining bits are intepreted as the actual number of reader currently using the lock
  53. * (which mean the lock is limited to 4294967288 concurrent readers but since it's a high number there
  54. * is no overflow safe guard to remain simple).
  55. */
  56. int rwlock;
  57. readonly LockRecursionPolicy recursionPolicy;
  58. AtomicBoolean upgradableTaken = new AtomicBoolean ();
  59. /* These events are just here for the sake of having a CPU-efficient sleep
  60. * when the wait for acquiring the lock is too long
  61. */
  62. #if NET_4_0
  63. ManualResetEventSlim upgradableEvent = new ManualResetEventSlim (true);
  64. ManualResetEventSlim writerDoneEvent = new ManualResetEventSlim (true);
  65. ManualResetEventSlim readerDoneEvent = new ManualResetEventSlim (true);
  66. #else
  67. ManualResetEvent upgradableEvent = new ManualResetEvent (true);
  68. ManualResetEvent writerDoneEvent = new ManualResetEvent (true);
  69. ManualResetEvent readerDoneEvent = new ManualResetEvent (true);
  70. #endif
  71. // This Stopwatch instance is used for all threads since .Elapsed is thread-safe
  72. readonly static Stopwatch sw = Stopwatch.StartNew ();
  73. /* For performance sake, these numbers are manipulated via classic increment and
  74. * decrement operations and thus are (as hinted by MSDN) not meant to be precise
  75. */
  76. int numReadWaiters, numUpgradeWaiters, numWriteWaiters;
  77. bool disposed;
  78. static int idPool = int.MinValue;
  79. readonly int id = Interlocked.Increment (ref idPool);
  80. /* This dictionary is instanciated per thread for all existing ReaderWriterLockSlim instance.
  81. * Each instance is defined by an internal integer id value used as a key in the dictionary.
  82. * to avoid keeping unneeded reference to the instance and getting in the way of the GC.
  83. * Since there is no LockCookie type here, all the useful per-thread infos concerning each
  84. * instance are kept here.
  85. */
  86. [ThreadStatic]
  87. static IDictionary<int, ThreadLockState> currentThreadState;
  88. public ReaderWriterLockSlim () : this (LockRecursionPolicy.NoRecursion)
  89. {
  90. }
  91. public ReaderWriterLockSlim (LockRecursionPolicy recursionPolicy)
  92. {
  93. this.recursionPolicy = recursionPolicy;
  94. }
  95. public void EnterReadLock ()
  96. {
  97. TryEnterReadLock (-1);
  98. }
  99. public bool TryEnterReadLock (int millisecondsTimeout)
  100. {
  101. ThreadLockState ctstate = CurrentThreadState;
  102. if (CheckState (ctstate, millisecondsTimeout, LockState.Read)) {
  103. ++ctstate.ReaderRecursiveCount;
  104. return true;
  105. }
  106. // This is downgrading from upgradable, no need for check since
  107. // we already have a sort-of read lock that's going to disappear
  108. // after user calls ExitUpgradeableReadLock.
  109. // Same idea when recursion is allowed and a write thread wants to
  110. // go for a Read too.
  111. if (ctstate.LockState.Has (LockState.Upgradable)
  112. || recursionPolicy == LockRecursionPolicy.SupportsRecursion) {
  113. Interlocked.Add (ref rwlock, RwRead);
  114. ctstate.LockState ^= LockState.Read;
  115. ++ctstate.ReaderRecursiveCount;
  116. return true;
  117. }
  118. ++numReadWaiters;
  119. int val = 0;
  120. long start = millisecondsTimeout == -1 ? 0 : sw.ElapsedMilliseconds;
  121. do {
  122. /* Check if a writer is present (RwWrite) or if there is someone waiting to
  123. * acquire a writer lock in the queue (RwWait | RwWaitUpgrade).
  124. */
  125. if ((rwlock & 0x7) > 0) {
  126. writerDoneEvent.Wait (ComputeTimeout (millisecondsTimeout, start));
  127. continue;
  128. }
  129. /* Optimistically try to add ourselves to the reader value
  130. * if the adding was too late and another writer came in between
  131. * we revert the operation.
  132. */
  133. if (((val = Interlocked.Add (ref rwlock, RwRead)) & 0x7) == 0) {
  134. /* If we are the first reader, reset the event to let other threads
  135. * sleep correctly if they try to acquire write lock
  136. */
  137. if (val >> RwReadBit == 1)
  138. readerDoneEvent.Reset ();
  139. ctstate.LockState ^= LockState.Read;
  140. ++ctstate.ReaderRecursiveCount;
  141. --numReadWaiters;
  142. return true;
  143. }
  144. Interlocked.Add (ref rwlock, -RwRead);
  145. writerDoneEvent.Wait (ComputeTimeout (millisecondsTimeout, start));
  146. } while (millisecondsTimeout == -1 || (sw.ElapsedMilliseconds - start) < millisecondsTimeout);
  147. --numReadWaiters;
  148. return false;
  149. }
  150. public bool TryEnterReadLock (TimeSpan timeout)
  151. {
  152. return TryEnterReadLock (CheckTimeout (timeout));
  153. }
  154. public void ExitReadLock ()
  155. {
  156. ThreadLockState ctstate = CurrentThreadState;
  157. if (!ctstate.LockState.Has (LockState.Read))
  158. throw new SynchronizationLockException ("The current thread has not entered the lock in read mode");
  159. ctstate.LockState ^= LockState.Read;
  160. --ctstate.ReaderRecursiveCount;
  161. if (Interlocked.Add (ref rwlock, -RwRead) >> RwReadBit == 0)
  162. readerDoneEvent.Set ();
  163. }
  164. public void EnterWriteLock ()
  165. {
  166. TryEnterWriteLock (-1);
  167. }
  168. public bool TryEnterWriteLock (int millisecondsTimeout)
  169. {
  170. ThreadLockState ctstate = CurrentThreadState;
  171. if (CheckState (ctstate, millisecondsTimeout, LockState.Write)) {
  172. ++ctstate.WriterRecursiveCount;
  173. return true;
  174. }
  175. ++numWriteWaiters;
  176. bool isUpgradable = ctstate.LockState.Has (LockState.Upgradable);
  177. /* If the code goes there that means we had a read lock beforehand
  178. * that need to be suppressed, we also take the opportunity to register
  179. * our interest in the write lock to avoid other write wannabe process
  180. * coming in the middle
  181. */
  182. if (isUpgradable && rwlock >= RwRead)
  183. if (Interlocked.Add (ref rwlock, RwWaitUpgrade - RwRead) >> RwReadBit == 0)
  184. readerDoneEvent.Set ();
  185. int stateCheck = isUpgradable ? RwWaitUpgrade : RwWait;
  186. long start = millisecondsTimeout == -1 ? 0 : sw.ElapsedMilliseconds;
  187. do {
  188. int state = rwlock;
  189. if (state <= stateCheck) {
  190. if (Interlocked.CompareExchange (ref rwlock, RwWrite, state) == state) {
  191. writerDoneEvent.Reset ();
  192. ctstate.LockState ^= LockState.Write;
  193. ++ctstate.WriterRecursiveCount;
  194. --numWriteWaiters;
  195. return true;
  196. }
  197. state = rwlock;
  198. }
  199. // We register our interest in taking the Write lock (if upgradeable it's already done)
  200. if (!isUpgradable)
  201. while ((state & RwWait) == 0 && Interlocked.CompareExchange (ref rwlock, state | RwWait, state) != state)
  202. state = rwlock;
  203. // Before falling to sleep
  204. do {
  205. if (rwlock <= stateCheck)
  206. break;
  207. if ((rwlock & RwWrite) != 0)
  208. writerDoneEvent.Wait (ComputeTimeout (millisecondsTimeout, start));
  209. else if ((rwlock >> RwReadBit) > 0)
  210. readerDoneEvent.Wait (ComputeTimeout (millisecondsTimeout, start));
  211. } while (millisecondsTimeout < 0 || (sw.ElapsedMilliseconds - start) < millisecondsTimeout);
  212. } while (millisecondsTimeout < 0 || (sw.ElapsedMilliseconds - start) < millisecondsTimeout);
  213. --numWriteWaiters;
  214. return false;
  215. }
  216. public bool TryEnterWriteLock (TimeSpan timeout)
  217. {
  218. return TryEnterWriteLock (CheckTimeout (timeout));
  219. }
  220. public void ExitWriteLock ()
  221. {
  222. ThreadLockState ctstate = CurrentThreadState;
  223. if (!ctstate.LockState.Has (LockState.Write))
  224. throw new SynchronizationLockException ("The current thread has not entered the lock in write mode");
  225. bool isUpgradable = ctstate.LockState.Has (LockState.Upgradable);
  226. ctstate.LockState ^= LockState.Write;
  227. --ctstate.WriterRecursiveCount;
  228. int value = Interlocked.Add (ref rwlock, isUpgradable ? RwRead - RwWrite : -RwWrite);
  229. writerDoneEvent.Set ();
  230. if (isUpgradable && value >> RwReadBit == 1)
  231. readerDoneEvent.Reset ();
  232. }
  233. public void EnterUpgradeableReadLock ()
  234. {
  235. TryEnterUpgradeableReadLock (-1);
  236. }
  237. //
  238. // Taking the Upgradable read lock is like taking a read lock
  239. // but we limit it to a single upgradable at a time.
  240. //
  241. public bool TryEnterUpgradeableReadLock (int millisecondsTimeout)
  242. {
  243. ThreadLockState ctstate = CurrentThreadState;
  244. if (CheckState (ctstate, millisecondsTimeout, LockState.Upgradable)) {
  245. ++ctstate.UpgradeableRecursiveCount;
  246. return true;
  247. }
  248. if (ctstate.LockState.Has (LockState.Read))
  249. throw new LockRecursionException ("The current thread has already entered read mode");
  250. ++numUpgradeWaiters;
  251. long start = millisecondsTimeout == -1 ? 0 : sw.ElapsedMilliseconds;
  252. // We first try to obtain the upgradeable right
  253. while (!upgradableEvent.IsSet () || !upgradableTaken.TryRelaxedSet ()) {
  254. if (millisecondsTimeout != -1 && (sw.ElapsedMilliseconds - start) > millisecondsTimeout) {
  255. --numUpgradeWaiters;
  256. return false;
  257. }
  258. upgradableEvent.Wait (ComputeTimeout (millisecondsTimeout, start));
  259. }
  260. upgradableEvent.Reset ();
  261. // Then it's a simple reader lock acquiring
  262. if (TryEnterReadLock (ComputeTimeout (millisecondsTimeout, start))) {
  263. ctstate.LockState = LockState.Upgradable;
  264. --numUpgradeWaiters;
  265. --ctstate.ReaderRecursiveCount;
  266. ++ctstate.UpgradeableRecursiveCount;
  267. return true;
  268. }
  269. upgradableTaken.Value = false;
  270. upgradableEvent.Set ();
  271. --numUpgradeWaiters;
  272. return false;
  273. }
  274. public bool TryEnterUpgradeableReadLock (TimeSpan timeout)
  275. {
  276. return TryEnterUpgradeableReadLock (CheckTimeout (timeout));
  277. }
  278. public void ExitUpgradeableReadLock ()
  279. {
  280. ThreadLockState ctstate = CurrentThreadState;
  281. if (!ctstate.LockState.Has (LockState.Upgradable | LockState.Read))
  282. throw new SynchronizationLockException ("The current thread has not entered the lock in upgradable mode");
  283. upgradableTaken.Value = false;
  284. upgradableEvent.Set ();
  285. ctstate.LockState ^= LockState.Upgradable;
  286. --ctstate.UpgradeableRecursiveCount;
  287. if (Interlocked.Add (ref rwlock, -RwRead) >> RwReadBit == 0)
  288. readerDoneEvent.Set ();
  289. }
  290. public void Dispose ()
  291. {
  292. disposed = true;
  293. }
  294. public bool IsReadLockHeld {
  295. get {
  296. return rwlock >= RwRead && CurrentThreadState.LockState.Has (LockState.Read);
  297. }
  298. }
  299. public bool IsWriteLockHeld {
  300. get {
  301. return (rwlock & RwWrite) > 0 && CurrentThreadState.LockState.Has (LockState.Write);
  302. }
  303. }
  304. public bool IsUpgradeableReadLockHeld {
  305. get {
  306. return upgradableTaken.Value && CurrentThreadState.LockState.Has (LockState.Upgradable);
  307. }
  308. }
  309. public int CurrentReadCount {
  310. get {
  311. return (rwlock >> RwReadBit) - (upgradableTaken.Value ? 1 : 0);
  312. }
  313. }
  314. public int RecursiveReadCount {
  315. get {
  316. return CurrentThreadState.ReaderRecursiveCount;
  317. }
  318. }
  319. public int RecursiveUpgradeCount {
  320. get {
  321. return CurrentThreadState.UpgradeableRecursiveCount;
  322. }
  323. }
  324. public int RecursiveWriteCount {
  325. get {
  326. return CurrentThreadState.WriterRecursiveCount;
  327. }
  328. }
  329. public int WaitingReadCount {
  330. get {
  331. return numReadWaiters;
  332. }
  333. }
  334. public int WaitingUpgradeCount {
  335. get {
  336. return numUpgradeWaiters;
  337. }
  338. }
  339. public int WaitingWriteCount {
  340. get {
  341. return numWriteWaiters;
  342. }
  343. }
  344. public LockRecursionPolicy RecursionPolicy {
  345. get {
  346. return recursionPolicy;
  347. }
  348. }
  349. ThreadLockState CurrentThreadState {
  350. get {
  351. if (currentThreadState == null)
  352. currentThreadState = new Dictionary<int, ThreadLockState> ();
  353. ThreadLockState state;
  354. if (!currentThreadState.TryGetValue (id, out state))
  355. currentThreadState[id] = state = new ThreadLockState ();
  356. return state;
  357. }
  358. }
  359. bool CheckState (ThreadLockState state, int millisecondsTimeout, LockState validState)
  360. {
  361. if (disposed)
  362. throw new ObjectDisposedException ("ReaderWriterLockSlim");
  363. if (millisecondsTimeout < Timeout.Infinite)
  364. throw new ArgumentOutOfRangeException ("millisecondsTimeout");
  365. // Detect and prevent recursion
  366. LockState ctstate = state.LockState;
  367. if (recursionPolicy == LockRecursionPolicy.NoRecursion)
  368. if ((ctstate != LockState.None && ctstate != LockState.Upgradable)
  369. || (ctstate == LockState.Upgradable && validState == LockState.Upgradable))
  370. throw new LockRecursionException ("The current thread has already a lock and recursion isn't supported");
  371. // If we already had right lock state, just return
  372. if (ctstate.Has (validState))
  373. return true;
  374. CheckRecursionAuthorization (ctstate, validState);
  375. return false;
  376. }
  377. static void CheckRecursionAuthorization (LockState ctstate, LockState desiredState)
  378. {
  379. // In read mode you can just enter Read recursively
  380. if (ctstate == LockState.Read)
  381. throw new LockRecursionException ();
  382. }
  383. static int CheckTimeout (TimeSpan timeout)
  384. {
  385. try {
  386. return checked ((int)timeout.TotalMilliseconds);
  387. } catch (System.OverflowException) {
  388. throw new ArgumentOutOfRangeException ("timeout");
  389. }
  390. }
  391. static int ComputeTimeout (int millisecondsTimeout, long start)
  392. {
  393. return millisecondsTimeout == -1 ? -1 : (int)Math.Max (sw.ElapsedMilliseconds - start - millisecondsTimeout, 1);
  394. }
  395. }
  396. }