ReaderWriterLockSlim.cs 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578
  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. }
  134. return true;
  135. }
  136. ++numReadWaiters;
  137. int val = 0;
  138. long start = millisecondsTimeout == -1 ? 0 : sw.ElapsedMilliseconds;
  139. do {
  140. /* Check if a writer is present (RwWrite) or if there is someone waiting to
  141. * acquire a writer lock in the queue (RwWait | RwWaitUpgrade).
  142. */
  143. if ((rwlock & (RwWrite | RwWait | RwWaitUpgrade)) > 0) {
  144. writerDoneEvent.Wait (ComputeTimeout (millisecondsTimeout, start));
  145. continue;
  146. }
  147. /* Optimistically try to add ourselves to the reader value
  148. * if the adding was too late and another writer came in between
  149. * we revert the operation.
  150. */
  151. RuntimeHelpers.PrepareConstrainedRegions ();
  152. try {}
  153. finally {
  154. if (((val = Interlocked.Add (ref rwlock, RwRead)) & (RwWrite | RwWait | RwWaitUpgrade)) == 0) {
  155. /* If we are the first reader, reset the event to let other threads
  156. * sleep correctly if they try to acquire write lock
  157. */
  158. if (val >> RwReadBit == 1)
  159. readerDoneEvent.Reset ();
  160. ctstate.LockState ^= LockState.Read;
  161. ++ctstate.ReaderRecursiveCount;
  162. --numReadWaiters;
  163. success = true;
  164. } else {
  165. Interlocked.Add (ref rwlock, -RwRead);
  166. }
  167. }
  168. if (success)
  169. return true;
  170. writerDoneEvent.Wait (ComputeTimeout (millisecondsTimeout, start));
  171. } while (millisecondsTimeout == -1 || (sw.ElapsedMilliseconds - start) < millisecondsTimeout);
  172. --numReadWaiters;
  173. return false;
  174. }
  175. public bool TryEnterReadLock (TimeSpan timeout)
  176. {
  177. return TryEnterReadLock (CheckTimeout (timeout));
  178. }
  179. public void ExitReadLock ()
  180. {
  181. RuntimeHelpers.PrepareConstrainedRegions ();
  182. try {}
  183. finally {
  184. ThreadLockState ctstate = CurrentThreadState;
  185. if (!ctstate.LockState.Has (LockState.Read))
  186. throw new SynchronizationLockException ("The current thread has not entered the lock in read mode");
  187. if (--ctstate.ReaderRecursiveCount == 0) {
  188. ctstate.LockState ^= LockState.Read;
  189. if (Interlocked.Add (ref rwlock, -RwRead) >> RwReadBit == 0)
  190. readerDoneEvent.Set ();
  191. }
  192. }
  193. }
  194. public void EnterWriteLock ()
  195. {
  196. TryEnterWriteLock (-1);
  197. }
  198. public bool TryEnterWriteLock (int millisecondsTimeout)
  199. {
  200. ThreadLockState ctstate = CurrentThreadState;
  201. if (CheckState (ctstate, millisecondsTimeout, LockState.Write)) {
  202. ++ctstate.WriterRecursiveCount;
  203. return true;
  204. }
  205. ++numWriteWaiters;
  206. bool isUpgradable = ctstate.LockState.Has (LockState.Upgradable);
  207. bool registered = false;
  208. bool success = false;
  209. RuntimeHelpers.PrepareConstrainedRegions ();
  210. try {
  211. /* If the code goes there that means we had a read lock beforehand
  212. * that need to be suppressed, we also take the opportunity to register
  213. * our interest in the write lock to avoid other write wannabe process
  214. * coming in the middle
  215. */
  216. if (isUpgradable && rwlock >= RwRead) {
  217. try {}
  218. finally {
  219. if (Interlocked.Add (ref rwlock, RwWaitUpgrade - RwRead) >> RwReadBit == 0)
  220. readerDoneEvent.Set ();
  221. registered = true;
  222. }
  223. }
  224. int stateCheck = isUpgradable ? RwWaitUpgrade : RwWait;
  225. long start = millisecondsTimeout == -1 ? 0 : sw.ElapsedMilliseconds;
  226. do {
  227. int state = rwlock;
  228. if (state <= stateCheck) {
  229. try {}
  230. finally {
  231. if (Interlocked.CompareExchange (ref rwlock, RwWrite, state) == state) {
  232. writerDoneEvent.Reset ();
  233. ctstate.LockState ^= LockState.Write;
  234. ++ctstate.WriterRecursiveCount;
  235. --numWriteWaiters;
  236. registered = false;
  237. success = true;
  238. }
  239. }
  240. if (success)
  241. return true;
  242. }
  243. state = rwlock;
  244. // We register our interest in taking the Write lock (if upgradeable it's already done)
  245. if (!isUpgradable) {
  246. while ((state & RwWait) == 0) {
  247. try {}
  248. finally {
  249. if (Interlocked.CompareExchange (ref rwlock, state | RwWait, state) == state)
  250. registered = true;
  251. }
  252. if (registered)
  253. break;
  254. state = rwlock;
  255. }
  256. }
  257. // Before falling to sleep
  258. do {
  259. if (rwlock <= stateCheck)
  260. break;
  261. if ((rwlock & RwWrite) != 0)
  262. writerDoneEvent.Wait (ComputeTimeout (millisecondsTimeout, start));
  263. else if ((rwlock >> RwReadBit) > 0)
  264. readerDoneEvent.Wait (ComputeTimeout (millisecondsTimeout, start));
  265. } while (millisecondsTimeout < 0 || (sw.ElapsedMilliseconds - start) < millisecondsTimeout);
  266. } while (millisecondsTimeout < 0 || (sw.ElapsedMilliseconds - start) < millisecondsTimeout);
  267. --numWriteWaiters;
  268. } finally {
  269. if (registered)
  270. Interlocked.Add (ref rwlock, isUpgradable ? -RwWaitUpgrade : -RwWait);
  271. }
  272. return false;
  273. }
  274. public bool TryEnterWriteLock (TimeSpan timeout)
  275. {
  276. return TryEnterWriteLock (CheckTimeout (timeout));
  277. }
  278. public void ExitWriteLock ()
  279. {
  280. RuntimeHelpers.PrepareConstrainedRegions ();
  281. try {}
  282. finally {
  283. ThreadLockState ctstate = CurrentThreadState;
  284. if (!ctstate.LockState.Has (LockState.Write))
  285. throw new SynchronizationLockException ("The current thread has not entered the lock in write mode");
  286. if (--ctstate.WriterRecursiveCount == 0) {
  287. bool isUpgradable = ctstate.LockState.Has (LockState.Upgradable);
  288. ctstate.LockState ^= LockState.Write;
  289. int value = Interlocked.Add (ref rwlock, isUpgradable ? RwRead - RwWrite : -RwWrite);
  290. writerDoneEvent.Set ();
  291. if (isUpgradable && value >> RwReadBit == 1)
  292. readerDoneEvent.Reset ();
  293. }
  294. }
  295. }
  296. public void EnterUpgradeableReadLock ()
  297. {
  298. TryEnterUpgradeableReadLock (-1);
  299. }
  300. //
  301. // Taking the Upgradable read lock is like taking a read lock
  302. // but we limit it to a single upgradable at a time.
  303. //
  304. public bool TryEnterUpgradeableReadLock (int millisecondsTimeout)
  305. {
  306. ThreadLockState ctstate = CurrentThreadState;
  307. if (CheckState (ctstate, millisecondsTimeout, LockState.Upgradable)) {
  308. ++ctstate.UpgradeableRecursiveCount;
  309. return true;
  310. }
  311. if (ctstate.LockState.Has (LockState.Read))
  312. throw new LockRecursionException ("The current thread has already entered read mode");
  313. ++numUpgradeWaiters;
  314. long start = millisecondsTimeout == -1 ? 0 : sw.ElapsedMilliseconds;
  315. bool taken = false;
  316. bool success = false;
  317. // We first try to obtain the upgradeable right
  318. try {
  319. while (!upgradableEvent.IsSet () || !taken) {
  320. try {}
  321. finally {
  322. taken = upgradableTaken.TryRelaxedSet ();
  323. }
  324. if (taken)
  325. break;
  326. if (millisecondsTimeout != -1 && (sw.ElapsedMilliseconds - start) > millisecondsTimeout) {
  327. --numUpgradeWaiters;
  328. return false;
  329. }
  330. upgradableEvent.Wait (ComputeTimeout (millisecondsTimeout, start));
  331. }
  332. upgradableEvent.Reset ();
  333. RuntimeHelpers.PrepareConstrainedRegions ();
  334. try {
  335. // Then it's a simple reader lock acquiring
  336. TryEnterReadLock (ComputeTimeout (millisecondsTimeout, start), ref success);
  337. } finally {
  338. if (success) {
  339. ctstate.LockState = LockState.Upgradable;
  340. --ctstate.ReaderRecursiveCount;
  341. ++ctstate.UpgradeableRecursiveCount;
  342. } else {
  343. upgradableTaken.Value = false;
  344. upgradableEvent.Set ();
  345. }
  346. }
  347. --numUpgradeWaiters;
  348. } catch {
  349. // An async exception occured, if we had taken the upgradable mode, release it
  350. if (taken && !success)
  351. upgradableTaken.Value = false;
  352. }
  353. return success;
  354. }
  355. public bool TryEnterUpgradeableReadLock (TimeSpan timeout)
  356. {
  357. return TryEnterUpgradeableReadLock (CheckTimeout (timeout));
  358. }
  359. public void ExitUpgradeableReadLock ()
  360. {
  361. RuntimeHelpers.PrepareConstrainedRegions ();
  362. try {}
  363. finally {
  364. ThreadLockState ctstate = CurrentThreadState;
  365. if (!ctstate.LockState.Has (LockState.Upgradable | LockState.Read))
  366. throw new SynchronizationLockException ("The current thread has not entered the lock in upgradable mode");
  367. if (--ctstate.UpgradeableRecursiveCount == 0) {
  368. upgradableTaken.Value = false;
  369. upgradableEvent.Set ();
  370. ctstate.LockState ^= LockState.Upgradable;
  371. if (Interlocked.Add (ref rwlock, -RwRead) >> RwReadBit == 0)
  372. readerDoneEvent.Set ();
  373. }
  374. }
  375. }
  376. public void Dispose ()
  377. {
  378. disposed = true;
  379. }
  380. public bool IsReadLockHeld {
  381. get {
  382. return rwlock >= RwRead && CurrentThreadState.LockState.Has (LockState.Read);
  383. }
  384. }
  385. public bool IsWriteLockHeld {
  386. get {
  387. return (rwlock & RwWrite) > 0 && CurrentThreadState.LockState.Has (LockState.Write);
  388. }
  389. }
  390. public bool IsUpgradeableReadLockHeld {
  391. get {
  392. return upgradableTaken.Value && CurrentThreadState.LockState.Has (LockState.Upgradable);
  393. }
  394. }
  395. public int CurrentReadCount {
  396. get {
  397. return (rwlock >> RwReadBit) - (upgradableTaken.Value ? 1 : 0);
  398. }
  399. }
  400. public int RecursiveReadCount {
  401. get {
  402. return CurrentThreadState.ReaderRecursiveCount;
  403. }
  404. }
  405. public int RecursiveUpgradeCount {
  406. get {
  407. return CurrentThreadState.UpgradeableRecursiveCount;
  408. }
  409. }
  410. public int RecursiveWriteCount {
  411. get {
  412. return CurrentThreadState.WriterRecursiveCount;
  413. }
  414. }
  415. public int WaitingReadCount {
  416. get {
  417. return numReadWaiters;
  418. }
  419. }
  420. public int WaitingUpgradeCount {
  421. get {
  422. return numUpgradeWaiters;
  423. }
  424. }
  425. public int WaitingWriteCount {
  426. get {
  427. return numWriteWaiters;
  428. }
  429. }
  430. public LockRecursionPolicy RecursionPolicy {
  431. get {
  432. return recursionPolicy;
  433. }
  434. }
  435. ThreadLockState CurrentThreadState {
  436. get {
  437. int tid = Thread.CurrentThread.ManagedThreadId;
  438. if (tid < fastStateCache.Length)
  439. return fastStateCache[tid] == null ? (fastStateCache[tid] = new ThreadLockState ()) : fastStateCache[tid];
  440. if (currentThreadState == null)
  441. currentThreadState = new Dictionary<int, ThreadLockState> ();
  442. ThreadLockState state;
  443. if (!currentThreadState.TryGetValue (id, out state))
  444. currentThreadState[id] = state = new ThreadLockState ();
  445. return state;
  446. }
  447. }
  448. bool CheckState (ThreadLockState state, int millisecondsTimeout, LockState validState)
  449. {
  450. if (disposed)
  451. throw new ObjectDisposedException ("ReaderWriterLockSlim");
  452. if (millisecondsTimeout < -1)
  453. throw new ArgumentOutOfRangeException ("millisecondsTimeout");
  454. // Detect and prevent recursion
  455. LockState ctstate = state.LockState;
  456. if (ctstate != LockState.None && noRecursion && (ctstate != LockState.Upgradable || validState == LockState.Upgradable))
  457. throw new LockRecursionException ("The current thread has already a lock and recursion isn't supported");
  458. if (noRecursion)
  459. return false;
  460. // If we already had right lock state, just return
  461. if (ctstate.Has (validState))
  462. return true;
  463. CheckRecursionAuthorization (ctstate, validState);
  464. return false;
  465. }
  466. static void CheckRecursionAuthorization (LockState ctstate, LockState desiredState)
  467. {
  468. // In read mode you can just enter Read recursively
  469. if (ctstate == LockState.Read)
  470. throw new LockRecursionException ();
  471. }
  472. static int CheckTimeout (TimeSpan timeout)
  473. {
  474. try {
  475. return checked ((int)timeout.TotalMilliseconds);
  476. } catch (System.OverflowException) {
  477. throw new ArgumentOutOfRangeException ("timeout");
  478. }
  479. }
  480. static int ComputeTimeout (int millisecondsTimeout, long start)
  481. {
  482. return millisecondsTimeout == -1 ? -1 : (int)Math.Max (sw.ElapsedMilliseconds - start - millisecondsTimeout, 1);
  483. }
  484. }
  485. }