ReaderWriterLockSlim.cs 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581
  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 4294967288 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 IDictionary<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. public 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. do {
  228. int state = rwlock;
  229. if (state <= stateCheck) {
  230. try {}
  231. finally {
  232. if (Interlocked.CompareExchange (ref rwlock, RwWrite, state) == state) {
  233. writerDoneEvent.Reset ();
  234. ctstate.LockState ^= LockState.Write;
  235. ++ctstate.WriterRecursiveCount;
  236. --numWriteWaiters;
  237. registered = false;
  238. success = true;
  239. }
  240. }
  241. if (success)
  242. return true;
  243. }
  244. state = rwlock;
  245. // We register our interest in taking the Write lock (if upgradeable it's already done)
  246. if (!isUpgradable) {
  247. while ((state & RwWait) == 0) {
  248. try {}
  249. finally {
  250. if (Interlocked.CompareExchange (ref rwlock, state | RwWait, state) == state)
  251. registered = true;
  252. }
  253. if (registered)
  254. break;
  255. state = rwlock;
  256. }
  257. }
  258. // Before falling to sleep
  259. do {
  260. if (rwlock <= stateCheck)
  261. break;
  262. if ((rwlock & RwWrite) != 0)
  263. writerDoneEvent.Wait (ComputeTimeout (millisecondsTimeout, start));
  264. else if ((rwlock >> RwReadBit) > 0)
  265. readerDoneEvent.Wait (ComputeTimeout (millisecondsTimeout, start));
  266. } while (millisecondsTimeout < 0 || (sw.ElapsedMilliseconds - start) < millisecondsTimeout);
  267. } while (millisecondsTimeout < 0 || (sw.ElapsedMilliseconds - start) < millisecondsTimeout);
  268. --numWriteWaiters;
  269. } finally {
  270. if (registered)
  271. Interlocked.Add (ref rwlock, isUpgradable ? -RwWaitUpgrade : -RwWait);
  272. }
  273. return false;
  274. }
  275. public bool TryEnterWriteLock (TimeSpan timeout)
  276. {
  277. return TryEnterWriteLock (CheckTimeout (timeout));
  278. }
  279. public void ExitWriteLock ()
  280. {
  281. RuntimeHelpers.PrepareConstrainedRegions ();
  282. try {}
  283. finally {
  284. ThreadLockState ctstate = CurrentThreadState;
  285. if (!ctstate.LockState.Has (LockState.Write))
  286. throw new SynchronizationLockException ("The current thread has not entered the lock in write mode");
  287. if (--ctstate.WriterRecursiveCount == 0) {
  288. bool isUpgradable = ctstate.LockState.Has (LockState.Upgradable);
  289. ctstate.LockState ^= LockState.Write;
  290. int value = Interlocked.Add (ref rwlock, isUpgradable ? RwRead - RwWrite : -RwWrite);
  291. writerDoneEvent.Set ();
  292. if (isUpgradable && value >> RwReadBit == 1)
  293. readerDoneEvent.Reset ();
  294. }
  295. }
  296. }
  297. public void EnterUpgradeableReadLock ()
  298. {
  299. TryEnterUpgradeableReadLock (-1);
  300. }
  301. //
  302. // Taking the Upgradable read lock is like taking a read lock
  303. // but we limit it to a single upgradable at a time.
  304. //
  305. public bool TryEnterUpgradeableReadLock (int millisecondsTimeout)
  306. {
  307. ThreadLockState ctstate = CurrentThreadState;
  308. if (CheckState (ctstate, millisecondsTimeout, LockState.Upgradable)) {
  309. ++ctstate.UpgradeableRecursiveCount;
  310. return true;
  311. }
  312. if (ctstate.LockState.Has (LockState.Read))
  313. throw new LockRecursionException ("The current thread has already entered read mode");
  314. ++numUpgradeWaiters;
  315. long start = millisecondsTimeout == -1 ? 0 : sw.ElapsedMilliseconds;
  316. bool taken = false;
  317. bool success = false;
  318. // We first try to obtain the upgradeable right
  319. try {
  320. while (!upgradableEvent.IsSet () || !taken) {
  321. try {}
  322. finally {
  323. taken = upgradableTaken.TryRelaxedSet ();
  324. }
  325. if (taken)
  326. break;
  327. if (millisecondsTimeout != -1 && (sw.ElapsedMilliseconds - start) > millisecondsTimeout) {
  328. --numUpgradeWaiters;
  329. return false;
  330. }
  331. upgradableEvent.Wait (ComputeTimeout (millisecondsTimeout, start));
  332. }
  333. upgradableEvent.Reset ();
  334. RuntimeHelpers.PrepareConstrainedRegions ();
  335. try {
  336. // Then it's a simple reader lock acquiring
  337. TryEnterReadLock (ComputeTimeout (millisecondsTimeout, start), ref success);
  338. } finally {
  339. if (success) {
  340. ctstate.LockState |= LockState.Upgradable;
  341. ctstate.LockState &= ~LockState.Read;
  342. --ctstate.ReaderRecursiveCount;
  343. ++ctstate.UpgradeableRecursiveCount;
  344. } else {
  345. upgradableTaken.Value = false;
  346. upgradableEvent.Set ();
  347. }
  348. }
  349. --numUpgradeWaiters;
  350. } catch {
  351. // An async exception occured, if we had taken the upgradable mode, release it
  352. if (taken && !success)
  353. upgradableTaken.Value = false;
  354. }
  355. return success;
  356. }
  357. public bool TryEnterUpgradeableReadLock (TimeSpan timeout)
  358. {
  359. return TryEnterUpgradeableReadLock (CheckTimeout (timeout));
  360. }
  361. public void ExitUpgradeableReadLock ()
  362. {
  363. RuntimeHelpers.PrepareConstrainedRegions ();
  364. try {}
  365. finally {
  366. ThreadLockState ctstate = CurrentThreadState;
  367. if (!ctstate.LockState.Has (LockState.Upgradable | LockState.Read))
  368. throw new SynchronizationLockException ("The current thread has not entered the lock in upgradable mode");
  369. if (--ctstate.UpgradeableRecursiveCount == 0) {
  370. upgradableTaken.Value = false;
  371. upgradableEvent.Set ();
  372. ctstate.LockState &= ~LockState.Upgradable;
  373. if (Interlocked.Add (ref rwlock, -RwRead) >> RwReadBit == 0)
  374. readerDoneEvent.Set ();
  375. }
  376. }
  377. }
  378. public void Dispose ()
  379. {
  380. disposed = true;
  381. }
  382. public bool IsReadLockHeld {
  383. get {
  384. return rwlock >= RwRead && CurrentThreadState.LockState.Has (LockState.Read);
  385. }
  386. }
  387. public bool IsWriteLockHeld {
  388. get {
  389. return (rwlock & RwWrite) > 0 && CurrentThreadState.LockState.Has (LockState.Write);
  390. }
  391. }
  392. public bool IsUpgradeableReadLockHeld {
  393. get {
  394. return upgradableTaken.Value && CurrentThreadState.LockState.Has (LockState.Upgradable);
  395. }
  396. }
  397. public int CurrentReadCount {
  398. get {
  399. return (rwlock >> RwReadBit) - (upgradableTaken.Value ? 1 : 0);
  400. }
  401. }
  402. public int RecursiveReadCount {
  403. get {
  404. return CurrentThreadState.ReaderRecursiveCount;
  405. }
  406. }
  407. public int RecursiveUpgradeCount {
  408. get {
  409. return CurrentThreadState.UpgradeableRecursiveCount;
  410. }
  411. }
  412. public int RecursiveWriteCount {
  413. get {
  414. return CurrentThreadState.WriterRecursiveCount;
  415. }
  416. }
  417. public int WaitingReadCount {
  418. get {
  419. return numReadWaiters;
  420. }
  421. }
  422. public int WaitingUpgradeCount {
  423. get {
  424. return numUpgradeWaiters;
  425. }
  426. }
  427. public int WaitingWriteCount {
  428. get {
  429. return numWriteWaiters;
  430. }
  431. }
  432. public LockRecursionPolicy RecursionPolicy {
  433. get {
  434. return recursionPolicy;
  435. }
  436. }
  437. ThreadLockState CurrentThreadState {
  438. get {
  439. int tid = Thread.CurrentThread.ManagedThreadId;
  440. if (tid < fastStateCache.Length)
  441. return fastStateCache[tid] == null ? (fastStateCache[tid] = new ThreadLockState ()) : fastStateCache[tid];
  442. if (currentThreadState == null)
  443. currentThreadState = new Dictionary<int, ThreadLockState> ();
  444. ThreadLockState state;
  445. if (!currentThreadState.TryGetValue (id, out state))
  446. currentThreadState[id] = state = new ThreadLockState ();
  447. return state;
  448. }
  449. }
  450. bool CheckState (ThreadLockState state, int millisecondsTimeout, LockState validState)
  451. {
  452. if (disposed)
  453. throw new ObjectDisposedException ("ReaderWriterLockSlim");
  454. if (millisecondsTimeout < -1)
  455. throw new ArgumentOutOfRangeException ("millisecondsTimeout");
  456. // Detect and prevent recursion
  457. LockState ctstate = state.LockState;
  458. if (ctstate != LockState.None && noRecursion && (!ctstate.Has (LockState.Upgradable) || validState == LockState.Upgradable))
  459. throw new LockRecursionException ("The current thread has already a lock and recursion isn't supported");
  460. if (noRecursion)
  461. return false;
  462. // If we already had right lock state, just return
  463. if (ctstate.Has (validState))
  464. return true;
  465. CheckRecursionAuthorization (ctstate, validState);
  466. return false;
  467. }
  468. static void CheckRecursionAuthorization (LockState ctstate, LockState desiredState)
  469. {
  470. // In read mode you can just enter Read recursively
  471. if (ctstate == LockState.Read)
  472. throw new LockRecursionException ();
  473. }
  474. static int CheckTimeout (TimeSpan timeout)
  475. {
  476. try {
  477. return checked ((int)timeout.TotalMilliseconds);
  478. } catch (System.OverflowException) {
  479. throw new ArgumentOutOfRangeException ("timeout");
  480. }
  481. }
  482. static int ComputeTimeout (int millisecondsTimeout, long start)
  483. {
  484. return millisecondsTimeout == -1 ? -1 : (int)Math.Max (sw.ElapsedMilliseconds - start - millisecondsTimeout, 1);
  485. }
  486. }
  487. }