ReaderWriterLockSlim.cs 17 KB

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