ReaderWriterLockSlim.cs 17 KB

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