ReaderWriterLockSlim.cs 62 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656
  1. // Licensed to the .NET Foundation under one or more agreements.
  2. // The .NET Foundation licenses this file to you under the MIT license.
  3. // See the LICENSE file in the project root for more information.
  4. using System.Diagnostics; // for TraceInformation
  5. using System.Diagnostics.CodeAnalysis;
  6. using System.Runtime.CompilerServices;
  7. namespace System.Threading
  8. {
  9. public enum LockRecursionPolicy
  10. {
  11. NoRecursion = 0,
  12. SupportsRecursion = 1,
  13. }
  14. //
  15. // ReaderWriterCount tracks how many of each kind of lock is held by each thread.
  16. // We keep a linked list for each thread, attached to a ThreadStatic field.
  17. // These are reused wherever possible, so that a given thread will only
  18. // allocate N of these, where N is the maximum number of locks held simultaneously
  19. // by that thread.
  20. //
  21. internal class ReaderWriterCount
  22. {
  23. // Which lock does this object belong to? This is a numeric ID for two reasons:
  24. // 1) We don't want this field to keep the lock object alive, and a WeakReference would
  25. // be too expensive.
  26. // 2) Setting the value of a long is faster than setting the value of a reference.
  27. // The "hot" paths in ReaderWriterLockSlim are short enough that this actually
  28. // matters.
  29. public long lockID;
  30. // How many reader locks does this thread hold on this ReaderWriterLockSlim instance?
  31. public int readercount;
  32. // Ditto for writer/upgrader counts. These are only used if the lock allows recursion.
  33. // But we have to have the fields on every ReaderWriterCount instance, because
  34. // we reuse it for different locks.
  35. public int writercount;
  36. public int upgradecount;
  37. // Next RWC in this thread's list.
  38. public ReaderWriterCount? next;
  39. }
  40. /// <summary>
  41. /// A reader-writer lock implementation that is intended to be simple, yet very
  42. /// efficient. In particular only 1 interlocked operation is taken for any lock
  43. /// operation (we use spin locks to achieve this). The spin lock is never held
  44. /// for more than a few instructions (in particular, we never call event APIs
  45. /// or in fact any non-trivial API while holding the spin lock).
  46. /// </summary>
  47. public class ReaderWriterLockSlim : IDisposable
  48. {
  49. // Specifying if the lock can be reacquired recursively.
  50. private readonly bool _fIsReentrant;
  51. // Lock specification for _spinLock: This lock protects exactly the local fields associated with this
  52. // instance of ReaderWriterLockSlim. It does NOT protect the memory associated with
  53. // the events that hang off this lock (eg writeEvent, readEvent upgradeEvent).
  54. private SpinLock _spinLock;
  55. // These variables allow use to avoid Setting events (which is expensive) if we don't have to.
  56. private uint _numWriteWaiters; // maximum number of threads that can be doing a WaitOne on the writeEvent
  57. private uint _numReadWaiters; // maximum number of threads that can be doing a WaitOne on the readEvent
  58. private uint _numWriteUpgradeWaiters; // maximum number of threads that can be doing a WaitOne on the upgradeEvent (at most 1).
  59. private uint _numUpgradeWaiters;
  60. private WaiterStates _waiterStates;
  61. private int _upgradeLockOwnerId;
  62. private int _writeLockOwnerId;
  63. // conditions we wait on.
  64. private EventWaitHandle? _writeEvent; // threads waiting to acquire a write lock go here.
  65. private EventWaitHandle? _readEvent; // threads waiting to acquire a read lock go here (will be released in bulk)
  66. private EventWaitHandle? _upgradeEvent; // thread waiting to acquire the upgrade lock
  67. private EventWaitHandle? _waitUpgradeEvent; // thread waiting to upgrade from the upgrade lock to a write lock go here (at most one)
  68. // Every lock instance has a unique ID, which is used by ReaderWriterCount to associate itself with the lock
  69. // without holding a reference to it.
  70. private static long s_nextLockID;
  71. private readonly long _lockID;
  72. // See comments on ReaderWriterCount.
  73. [ThreadStatic]
  74. private static ReaderWriterCount? t_rwc;
  75. private bool _fUpgradeThreadHoldingRead;
  76. private const int MaxSpinCount = 20;
  77. // The uint, that contains info like if the writer lock is held, num of
  78. // readers etc.
  79. private uint _owners;
  80. // Various R/W masks
  81. // Note:
  82. // The Uint is divided as follows:
  83. //
  84. // Writer-Owned Waiting-Writers Waiting Upgraders Num-Readers
  85. // 31 30 29 28.......0
  86. //
  87. // Dividing the uint, allows to vastly simplify logic for checking if a
  88. // reader should go in etc. Setting the writer bit will automatically
  89. // make the value of the uint much larger than the max num of readers
  90. // allowed, thus causing the check for max_readers to fail.
  91. private const uint WRITER_HELD = 0x80000000;
  92. private const uint WAITING_WRITERS = 0x40000000;
  93. private const uint WAITING_UPGRADER = 0x20000000;
  94. // The max readers is actually one less then its theoretical max.
  95. // This is done in order to prevent reader count overflows. If the reader
  96. // count reaches max, other readers will wait.
  97. private const uint MAX_READER = 0x10000000 - 2;
  98. private const uint READER_MASK = 0x10000000 - 1;
  99. private bool _fDisposed;
  100. private void InitializeThreadCounts()
  101. {
  102. _upgradeLockOwnerId = -1;
  103. _writeLockOwnerId = -1;
  104. }
  105. public ReaderWriterLockSlim()
  106. : this(LockRecursionPolicy.NoRecursion)
  107. {
  108. }
  109. public ReaderWriterLockSlim(LockRecursionPolicy recursionPolicy)
  110. {
  111. if (recursionPolicy == LockRecursionPolicy.SupportsRecursion)
  112. {
  113. _fIsReentrant = true;
  114. }
  115. InitializeThreadCounts();
  116. _waiterStates = WaiterStates.NoWaiters;
  117. _lockID = Interlocked.Increment(ref s_nextLockID);
  118. }
  119. private bool HasNoWaiters
  120. {
  121. get
  122. {
  123. #if DEBUG
  124. Debug.Assert(_spinLock.IsHeld);
  125. #endif
  126. return (_waiterStates & WaiterStates.NoWaiters) != WaiterStates.None;
  127. }
  128. set
  129. {
  130. #if DEBUG
  131. Debug.Assert(_spinLock.IsHeld);
  132. #endif
  133. if (value)
  134. {
  135. _waiterStates |= WaiterStates.NoWaiters;
  136. }
  137. else
  138. {
  139. _waiterStates &= ~WaiterStates.NoWaiters;
  140. }
  141. }
  142. }
  143. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  144. private static bool IsRWEntryEmpty(ReaderWriterCount rwc)
  145. {
  146. if (rwc.lockID == 0)
  147. return true;
  148. else if (rwc.readercount == 0 && rwc.writercount == 0 && rwc.upgradecount == 0)
  149. return true;
  150. else
  151. return false;
  152. }
  153. private bool IsRwHashEntryChanged(ReaderWriterCount lrwc)
  154. {
  155. return lrwc.lockID != _lockID;
  156. }
  157. /// <summary>
  158. /// This routine retrieves/sets the per-thread counts needed to enforce the
  159. /// various rules related to acquiring the lock.
  160. ///
  161. /// DontAllocate is set to true if the caller just wants to get an existing
  162. /// entry for this thread, but doesn't want to add one if an existing one
  163. /// could not be found.
  164. /// </summary>
  165. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  166. private ReaderWriterCount? GetThreadRWCount(bool dontAllocate)
  167. {
  168. ReaderWriterCount? rwc = t_rwc;
  169. ReaderWriterCount? empty = null;
  170. while (rwc != null)
  171. {
  172. if (rwc.lockID == _lockID)
  173. return rwc;
  174. if (!dontAllocate && empty == null && IsRWEntryEmpty(rwc))
  175. empty = rwc;
  176. rwc = rwc.next;
  177. }
  178. if (dontAllocate)
  179. return null;
  180. if (empty == null)
  181. {
  182. empty = new ReaderWriterCount();
  183. empty.next = t_rwc;
  184. t_rwc = empty;
  185. }
  186. empty.lockID = _lockID;
  187. return empty;
  188. }
  189. public void EnterReadLock()
  190. {
  191. TryEnterReadLock(-1);
  192. }
  193. //
  194. // Common timeout support
  195. //
  196. private struct TimeoutTracker
  197. {
  198. private readonly int _total;
  199. private readonly int _start;
  200. public TimeoutTracker(TimeSpan timeout)
  201. {
  202. long ltm = (long)timeout.TotalMilliseconds;
  203. if (ltm < -1 || ltm > (long)int.MaxValue)
  204. throw new ArgumentOutOfRangeException(nameof(timeout));
  205. _total = (int)ltm;
  206. if (_total != -1 && _total != 0)
  207. _start = Environment.TickCount;
  208. else
  209. _start = 0;
  210. }
  211. public TimeoutTracker(int millisecondsTimeout)
  212. {
  213. if (millisecondsTimeout < -1)
  214. throw new ArgumentOutOfRangeException(nameof(millisecondsTimeout));
  215. _total = millisecondsTimeout;
  216. if (_total != -1 && _total != 0)
  217. _start = Environment.TickCount;
  218. else
  219. _start = 0;
  220. }
  221. public int RemainingMilliseconds
  222. {
  223. get
  224. {
  225. if (_total == -1 || _total == 0)
  226. return _total;
  227. int elapsed = Environment.TickCount - _start;
  228. // elapsed may be negative if TickCount has overflowed by 2^31 milliseconds.
  229. if (elapsed < 0 || elapsed >= _total)
  230. return 0;
  231. return _total - elapsed;
  232. }
  233. }
  234. public bool IsExpired => RemainingMilliseconds == 0;
  235. }
  236. public bool TryEnterReadLock(TimeSpan timeout)
  237. {
  238. return TryEnterReadLock(new TimeoutTracker(timeout));
  239. }
  240. public bool TryEnterReadLock(int millisecondsTimeout)
  241. {
  242. return TryEnterReadLock(new TimeoutTracker(millisecondsTimeout));
  243. }
  244. private bool TryEnterReadLock(TimeoutTracker timeout)
  245. {
  246. return TryEnterReadLockCore(timeout);
  247. }
  248. private bool TryEnterReadLockCore(TimeoutTracker timeout)
  249. {
  250. if (_fDisposed)
  251. throw new ObjectDisposedException(null);
  252. ReaderWriterCount lrwc;
  253. int id = Environment.CurrentManagedThreadId;
  254. if (!_fIsReentrant)
  255. {
  256. if (id == _writeLockOwnerId)
  257. {
  258. // Check for AW->AR
  259. throw new LockRecursionException(SR.LockRecursionException_ReadAfterWriteNotAllowed);
  260. }
  261. _spinLock.Enter(EnterSpinLockReason.EnterAnyRead);
  262. lrwc = GetThreadRWCount(dontAllocate: false)!;
  263. // Check if the reader lock is already acquired. Note, we could
  264. // check the presence of a reader by not allocating rwc (But that
  265. // would lead to two lookups in the common case. It's better to keep
  266. // a count in the structure).
  267. if (lrwc.readercount > 0)
  268. {
  269. _spinLock.Exit();
  270. throw new LockRecursionException(SR.LockRecursionException_RecursiveReadNotAllowed);
  271. }
  272. else if (id == _upgradeLockOwnerId)
  273. {
  274. // The upgrade lock is already held.
  275. // Update the global read counts and exit.
  276. lrwc.readercount++;
  277. _owners++;
  278. _spinLock.Exit();
  279. return true;
  280. }
  281. }
  282. else
  283. {
  284. _spinLock.Enter(EnterSpinLockReason.EnterAnyRead);
  285. lrwc = GetThreadRWCount(dontAllocate: false)!;
  286. if (lrwc.readercount > 0)
  287. {
  288. lrwc.readercount++;
  289. _spinLock.Exit();
  290. return true;
  291. }
  292. else if (id == _upgradeLockOwnerId)
  293. {
  294. // The upgrade lock is already held.
  295. // Update the global read counts and exit.
  296. lrwc.readercount++;
  297. _owners++;
  298. _spinLock.Exit();
  299. _fUpgradeThreadHoldingRead = true;
  300. return true;
  301. }
  302. else if (id == _writeLockOwnerId)
  303. {
  304. // The write lock is already held.
  305. // Update global read counts here,
  306. lrwc.readercount++;
  307. _owners++;
  308. _spinLock.Exit();
  309. return true;
  310. }
  311. }
  312. bool retVal = true;
  313. int spinCount = 0;
  314. while (true)
  315. {
  316. // We can enter a read lock if there are only read-locks have been given out
  317. // and a writer is not trying to get in.
  318. if (_owners < MAX_READER)
  319. {
  320. // Good case, there is no contention, we are basically done
  321. _owners++; // Indicate we have another reader
  322. lrwc.readercount++;
  323. break;
  324. }
  325. if (timeout.IsExpired)
  326. {
  327. _spinLock.Exit();
  328. return false;
  329. }
  330. if (spinCount < MaxSpinCount && ShouldSpinForEnterAnyRead())
  331. {
  332. _spinLock.Exit();
  333. spinCount++;
  334. SpinWait(spinCount);
  335. _spinLock.Enter(EnterSpinLockReason.EnterAnyRead);
  336. // The per-thread structure may have been recycled as the lock is acquired (due to message pumping), load again.
  337. if (IsRwHashEntryChanged(lrwc))
  338. lrwc = GetThreadRWCount(dontAllocate: false)!;
  339. continue;
  340. }
  341. // Drat, we need to wait. Mark that we have waiters and wait.
  342. if (_readEvent == null) // Create the needed event
  343. {
  344. LazyCreateEvent(ref _readEvent, EnterLockType.Read);
  345. if (IsRwHashEntryChanged(lrwc))
  346. lrwc = GetThreadRWCount(dontAllocate: false)!;
  347. continue; // since we left the lock, start over.
  348. }
  349. retVal = WaitOnEvent(_readEvent, ref _numReadWaiters, timeout, EnterLockType.Read);
  350. if (!retVal)
  351. {
  352. return false;
  353. }
  354. if (IsRwHashEntryChanged(lrwc))
  355. lrwc = GetThreadRWCount(dontAllocate: false)!;
  356. }
  357. _spinLock.Exit();
  358. return retVal;
  359. }
  360. public void EnterWriteLock()
  361. {
  362. TryEnterWriteLock(-1);
  363. }
  364. public bool TryEnterWriteLock(TimeSpan timeout)
  365. {
  366. return TryEnterWriteLock(new TimeoutTracker(timeout));
  367. }
  368. public bool TryEnterWriteLock(int millisecondsTimeout)
  369. {
  370. return TryEnterWriteLock(new TimeoutTracker(millisecondsTimeout));
  371. }
  372. private bool TryEnterWriteLock(TimeoutTracker timeout)
  373. {
  374. return TryEnterWriteLockCore(timeout);
  375. }
  376. private bool TryEnterWriteLockCore(TimeoutTracker timeout)
  377. {
  378. if (_fDisposed)
  379. throw new ObjectDisposedException(null);
  380. int id = Environment.CurrentManagedThreadId;
  381. ReaderWriterCount? lrwc;
  382. bool upgradingToWrite = false;
  383. if (!_fIsReentrant)
  384. {
  385. EnterSpinLockReason enterMyLockReason;
  386. if (id == _writeLockOwnerId)
  387. {
  388. // Check for AW->AW
  389. throw new LockRecursionException(SR.LockRecursionException_RecursiveWriteNotAllowed);
  390. }
  391. else if (id == _upgradeLockOwnerId)
  392. {
  393. // AU->AW case is allowed once.
  394. upgradingToWrite = true;
  395. enterMyLockReason = EnterSpinLockReason.UpgradeToWrite;
  396. }
  397. else
  398. {
  399. enterMyLockReason = EnterSpinLockReason.EnterWrite;
  400. }
  401. _spinLock.Enter(enterMyLockReason);
  402. lrwc = GetThreadRWCount(dontAllocate: true);
  403. // Can't acquire write lock with reader lock held.
  404. if (lrwc != null && lrwc.readercount > 0)
  405. {
  406. _spinLock.Exit();
  407. throw new LockRecursionException(SR.LockRecursionException_WriteAfterReadNotAllowed);
  408. }
  409. }
  410. else
  411. {
  412. EnterSpinLockReason enterMyLockReason;
  413. if (id == _writeLockOwnerId)
  414. {
  415. enterMyLockReason = EnterSpinLockReason.EnterRecursiveWrite;
  416. }
  417. else if (id == _upgradeLockOwnerId)
  418. {
  419. enterMyLockReason = EnterSpinLockReason.UpgradeToWrite;
  420. }
  421. else
  422. {
  423. enterMyLockReason = EnterSpinLockReason.EnterWrite;
  424. }
  425. _spinLock.Enter(enterMyLockReason);
  426. lrwc = GetThreadRWCount(dontAllocate: false)!;
  427. if (id == _writeLockOwnerId)
  428. {
  429. lrwc.writercount++;
  430. _spinLock.Exit();
  431. return true;
  432. }
  433. else if (id == _upgradeLockOwnerId)
  434. {
  435. upgradingToWrite = true;
  436. }
  437. else if (lrwc.readercount > 0)
  438. {
  439. // Write locks may not be acquired if only read locks have been
  440. // acquired.
  441. _spinLock.Exit();
  442. throw new LockRecursionException(SR.LockRecursionException_WriteAfterReadNotAllowed);
  443. }
  444. }
  445. bool retVal = true;
  446. int spinCount = 0;
  447. while (true)
  448. {
  449. if (IsWriterAcquired())
  450. {
  451. // Good case, there is no contention, we are basically done
  452. SetWriterAcquired();
  453. break;
  454. }
  455. // Check if there is just one upgrader, and no readers.
  456. // Assumption: Only one thread can have the upgrade lock, so the
  457. // following check will fail for all other threads that may sneak in
  458. // when the upgrading thread is waiting.
  459. if (upgradingToWrite)
  460. {
  461. uint readercount = GetNumReaders();
  462. if (readercount == 1)
  463. {
  464. // Good case again, there is just one upgrader, and no readers.
  465. SetWriterAcquired(); // indicate we have a writer.
  466. break;
  467. }
  468. else if (readercount == 2)
  469. {
  470. if (lrwc != null)
  471. {
  472. if (IsRwHashEntryChanged(lrwc))
  473. lrwc = GetThreadRWCount(dontAllocate: false)!;
  474. if (lrwc.readercount > 0)
  475. {
  476. // This check is needed for EU->ER->EW case, as the owner count will be two.
  477. Debug.Assert(_fIsReentrant);
  478. Debug.Assert(_fUpgradeThreadHoldingRead);
  479. // Good case again, there is just one upgrader, and no readers.
  480. SetWriterAcquired(); // indicate we have a writer.
  481. break;
  482. }
  483. }
  484. }
  485. }
  486. if (timeout.IsExpired)
  487. {
  488. _spinLock.Exit();
  489. return false;
  490. }
  491. if (spinCount < MaxSpinCount && ShouldSpinForEnterAnyWrite(upgradingToWrite))
  492. {
  493. _spinLock.Exit();
  494. spinCount++;
  495. SpinWait(spinCount);
  496. _spinLock.Enter(upgradingToWrite ? EnterSpinLockReason.UpgradeToWrite : EnterSpinLockReason.EnterWrite);
  497. continue;
  498. }
  499. if (upgradingToWrite)
  500. {
  501. if (_waitUpgradeEvent == null) // Create the needed event
  502. {
  503. LazyCreateEvent(ref _waitUpgradeEvent, EnterLockType.UpgradeToWrite);
  504. continue; // since we left the lock, start over.
  505. }
  506. Debug.Assert(_numWriteUpgradeWaiters == 0, "There can be at most one thread with the upgrade lock held.");
  507. retVal = WaitOnEvent(_waitUpgradeEvent, ref _numWriteUpgradeWaiters, timeout, EnterLockType.UpgradeToWrite);
  508. // The lock is not held in case of failure.
  509. if (!retVal)
  510. return false;
  511. }
  512. else
  513. {
  514. // Drat, we need to wait. Mark that we have waiters and wait.
  515. if (_writeEvent == null) // create the needed event.
  516. {
  517. LazyCreateEvent(ref _writeEvent, EnterLockType.Write);
  518. continue; // since we left the lock, start over.
  519. }
  520. retVal = WaitOnEvent(_writeEvent, ref _numWriteWaiters, timeout, EnterLockType.Write);
  521. // The lock is not held in case of failure.
  522. if (!retVal)
  523. return false;
  524. }
  525. }
  526. Debug.Assert((_owners & WRITER_HELD) > 0);
  527. if (_fIsReentrant)
  528. {
  529. Debug.Assert(lrwc != null, "Initialized based on _fIsReentrant earlier in the method");
  530. if (IsRwHashEntryChanged(lrwc))
  531. lrwc = GetThreadRWCount(dontAllocate: false)!;
  532. lrwc.writercount++;
  533. }
  534. _spinLock.Exit();
  535. _writeLockOwnerId = id;
  536. return true;
  537. }
  538. public void EnterUpgradeableReadLock()
  539. {
  540. TryEnterUpgradeableReadLock(-1);
  541. }
  542. public bool TryEnterUpgradeableReadLock(TimeSpan timeout)
  543. {
  544. return TryEnterUpgradeableReadLock(new TimeoutTracker(timeout));
  545. }
  546. public bool TryEnterUpgradeableReadLock(int millisecondsTimeout)
  547. {
  548. return TryEnterUpgradeableReadLock(new TimeoutTracker(millisecondsTimeout));
  549. }
  550. private bool TryEnterUpgradeableReadLock(TimeoutTracker timeout)
  551. {
  552. return TryEnterUpgradeableReadLockCore(timeout);
  553. }
  554. private bool TryEnterUpgradeableReadLockCore(TimeoutTracker timeout)
  555. {
  556. if (_fDisposed)
  557. throw new ObjectDisposedException(null);
  558. int id = Environment.CurrentManagedThreadId;
  559. ReaderWriterCount? lrwc;
  560. if (!_fIsReentrant)
  561. {
  562. if (id == _upgradeLockOwnerId)
  563. {
  564. // Check for AU->AU
  565. throw new LockRecursionException(SR.LockRecursionException_RecursiveUpgradeNotAllowed);
  566. }
  567. else if (id == _writeLockOwnerId)
  568. {
  569. // Check for AU->AW
  570. throw new LockRecursionException(SR.LockRecursionException_UpgradeAfterWriteNotAllowed);
  571. }
  572. _spinLock.Enter(EnterSpinLockReason.EnterAnyRead);
  573. lrwc = GetThreadRWCount(dontAllocate: true);
  574. // Can't acquire upgrade lock with reader lock held.
  575. if (lrwc != null && lrwc.readercount > 0)
  576. {
  577. _spinLock.Exit();
  578. throw new LockRecursionException(SR.LockRecursionException_UpgradeAfterReadNotAllowed);
  579. }
  580. }
  581. else
  582. {
  583. _spinLock.Enter(EnterSpinLockReason.EnterAnyRead);
  584. lrwc = GetThreadRWCount(dontAllocate: false)!;
  585. if (id == _upgradeLockOwnerId)
  586. {
  587. lrwc.upgradecount++;
  588. _spinLock.Exit();
  589. return true;
  590. }
  591. else if (id == _writeLockOwnerId)
  592. {
  593. // Write lock is already held, Just update the global state
  594. // to show presence of upgrader.
  595. Debug.Assert((_owners & WRITER_HELD) > 0);
  596. _owners++;
  597. _upgradeLockOwnerId = id;
  598. lrwc.upgradecount++;
  599. if (lrwc.readercount > 0)
  600. _fUpgradeThreadHoldingRead = true;
  601. _spinLock.Exit();
  602. return true;
  603. }
  604. else if (lrwc.readercount > 0)
  605. {
  606. // Upgrade locks may not be acquired if only read locks have been
  607. // acquired.
  608. _spinLock.Exit();
  609. throw new LockRecursionException(SR.LockRecursionException_UpgradeAfterReadNotAllowed);
  610. }
  611. }
  612. bool retVal = true;
  613. int spinCount = 0;
  614. while (true)
  615. {
  616. // Once an upgrade lock is taken, it's like having a reader lock held
  617. // until upgrade or downgrade operations are performed.
  618. if ((_upgradeLockOwnerId == -1) && (_owners < MAX_READER))
  619. {
  620. _owners++;
  621. _upgradeLockOwnerId = id;
  622. break;
  623. }
  624. if (timeout.IsExpired)
  625. {
  626. _spinLock.Exit();
  627. return false;
  628. }
  629. if (spinCount < MaxSpinCount && ShouldSpinForEnterAnyRead())
  630. {
  631. _spinLock.Exit();
  632. spinCount++;
  633. SpinWait(spinCount);
  634. _spinLock.Enter(EnterSpinLockReason.EnterAnyRead);
  635. continue;
  636. }
  637. // Drat, we need to wait. Mark that we have waiters and wait.
  638. if (_upgradeEvent == null) // Create the needed event
  639. {
  640. LazyCreateEvent(ref _upgradeEvent, EnterLockType.UpgradeableRead);
  641. continue; // since we left the lock, start over.
  642. }
  643. // Only one thread with the upgrade lock held can proceed.
  644. retVal = WaitOnEvent(_upgradeEvent, ref _numUpgradeWaiters, timeout, EnterLockType.UpgradeableRead);
  645. if (!retVal)
  646. return false;
  647. }
  648. if (_fIsReentrant)
  649. {
  650. // The lock may have been dropped getting here, so make a quick check to see whether some other
  651. // thread did not grab the entry.
  652. Debug.Assert(lrwc != null, "Initialized based on _fIsReentrant earlier in the method");
  653. if (IsRwHashEntryChanged(lrwc))
  654. lrwc = GetThreadRWCount(dontAllocate: false)!;
  655. lrwc.upgradecount++;
  656. }
  657. _spinLock.Exit();
  658. return true;
  659. }
  660. public void ExitReadLock()
  661. {
  662. _spinLock.Enter(EnterSpinLockReason.ExitAnyRead);
  663. ReaderWriterCount? lrwc = GetThreadRWCount(dontAllocate: true);
  664. if (lrwc == null || lrwc.readercount < 1)
  665. {
  666. // You have to be holding the read lock to make this call.
  667. _spinLock.Exit();
  668. throw new SynchronizationLockException(SR.SynchronizationLockException_MisMatchedRead);
  669. }
  670. if (_fIsReentrant)
  671. {
  672. if (lrwc.readercount > 1)
  673. {
  674. lrwc.readercount--;
  675. _spinLock.Exit();
  676. return;
  677. }
  678. if (Environment.CurrentManagedThreadId == _upgradeLockOwnerId)
  679. {
  680. _fUpgradeThreadHoldingRead = false;
  681. }
  682. }
  683. Debug.Assert(_owners > 0, "ReleasingReaderLock: releasing lock and no read lock taken");
  684. --_owners;
  685. Debug.Assert(lrwc.readercount == 1);
  686. lrwc.readercount--;
  687. ExitAndWakeUpAppropriateWaiters();
  688. }
  689. public void ExitWriteLock()
  690. {
  691. ReaderWriterCount lrwc;
  692. if (!_fIsReentrant)
  693. {
  694. if (Environment.CurrentManagedThreadId != _writeLockOwnerId)
  695. {
  696. // You have to be holding the write lock to make this call.
  697. throw new SynchronizationLockException(SR.SynchronizationLockException_MisMatchedWrite);
  698. }
  699. _spinLock.Enter(EnterSpinLockReason.ExitAnyWrite);
  700. }
  701. else
  702. {
  703. _spinLock.Enter(EnterSpinLockReason.ExitAnyWrite);
  704. lrwc = GetThreadRWCount(dontAllocate: false)!;
  705. if (lrwc == null)
  706. {
  707. _spinLock.Exit();
  708. throw new SynchronizationLockException(SR.SynchronizationLockException_MisMatchedWrite);
  709. }
  710. if (lrwc.writercount < 1)
  711. {
  712. _spinLock.Exit();
  713. throw new SynchronizationLockException(SR.SynchronizationLockException_MisMatchedWrite);
  714. }
  715. lrwc.writercount--;
  716. if (lrwc.writercount > 0)
  717. {
  718. _spinLock.Exit();
  719. return;
  720. }
  721. }
  722. Debug.Assert((_owners & WRITER_HELD) > 0, "Calling ReleaseWriterLock when no write lock is held");
  723. ClearWriterAcquired();
  724. _writeLockOwnerId = -1;
  725. ExitAndWakeUpAppropriateWaiters();
  726. }
  727. public void ExitUpgradeableReadLock()
  728. {
  729. ReaderWriterCount? lrwc;
  730. if (!_fIsReentrant)
  731. {
  732. if (Environment.CurrentManagedThreadId != _upgradeLockOwnerId)
  733. {
  734. // You have to be holding the upgrade lock to make this call.
  735. throw new SynchronizationLockException(SR.SynchronizationLockException_MisMatchedUpgrade);
  736. }
  737. _spinLock.Enter(EnterSpinLockReason.ExitAnyRead);
  738. }
  739. else
  740. {
  741. _spinLock.Enter(EnterSpinLockReason.ExitAnyRead);
  742. lrwc = GetThreadRWCount(dontAllocate: true);
  743. if (lrwc == null)
  744. {
  745. _spinLock.Exit();
  746. throw new SynchronizationLockException(SR.SynchronizationLockException_MisMatchedUpgrade);
  747. }
  748. if (lrwc.upgradecount < 1)
  749. {
  750. _spinLock.Exit();
  751. throw new SynchronizationLockException(SR.SynchronizationLockException_MisMatchedUpgrade);
  752. }
  753. lrwc.upgradecount--;
  754. if (lrwc.upgradecount > 0)
  755. {
  756. _spinLock.Exit();
  757. return;
  758. }
  759. _fUpgradeThreadHoldingRead = false;
  760. }
  761. _owners--;
  762. _upgradeLockOwnerId = -1;
  763. ExitAndWakeUpAppropriateWaiters();
  764. }
  765. /// <summary>
  766. /// A routine for lazily creating a event outside the lock (so if errors
  767. /// happen they are outside the lock and that we don't do much work
  768. /// while holding a spin lock). If all goes well, reenter the lock and
  769. /// set 'waitEvent'
  770. /// </summary>
  771. private void LazyCreateEvent([NotNull] ref EventWaitHandle? waitEvent, EnterLockType enterLockType)
  772. {
  773. #if DEBUG
  774. Debug.Assert(_spinLock.IsHeld);
  775. Debug.Assert(waitEvent == null);
  776. #endif
  777. _spinLock.Exit();
  778. var newEvent =
  779. new EventWaitHandle(
  780. false,
  781. enterLockType == EnterLockType.Read ? EventResetMode.ManualReset : EventResetMode.AutoReset);
  782. EnterSpinLockReason enterMyLockReason;
  783. switch (enterLockType)
  784. {
  785. case EnterLockType.Read:
  786. case EnterLockType.UpgradeableRead:
  787. enterMyLockReason = EnterSpinLockReason.EnterAnyRead | EnterSpinLockReason.Wait;
  788. break;
  789. case EnterLockType.Write:
  790. enterMyLockReason = EnterSpinLockReason.EnterWrite | EnterSpinLockReason.Wait;
  791. break;
  792. default:
  793. Debug.Assert(enterLockType == EnterLockType.UpgradeToWrite);
  794. enterMyLockReason = EnterSpinLockReason.UpgradeToWrite | EnterSpinLockReason.Wait;
  795. break;
  796. }
  797. _spinLock.Enter(enterMyLockReason);
  798. if (waitEvent == null) // maybe someone snuck in.
  799. waitEvent = newEvent;
  800. else
  801. newEvent.Dispose();
  802. }
  803. /// <summary>
  804. /// Waits on 'waitEvent' with a timeout
  805. /// Before the wait 'numWaiters' is incremented and is restored before leaving this routine.
  806. /// </summary>
  807. private bool WaitOnEvent(
  808. EventWaitHandle waitEvent,
  809. ref uint numWaiters,
  810. TimeoutTracker timeout,
  811. EnterLockType enterLockType)
  812. {
  813. #if DEBUG
  814. Debug.Assert(_spinLock.IsHeld);
  815. #endif
  816. WaiterStates waiterSignaledState = WaiterStates.None;
  817. EnterSpinLockReason enterMyLockReason;
  818. switch (enterLockType)
  819. {
  820. case EnterLockType.UpgradeableRead:
  821. waiterSignaledState = WaiterStates.UpgradeableReadWaiterSignaled;
  822. goto case EnterLockType.Read;
  823. case EnterLockType.Read:
  824. enterMyLockReason = EnterSpinLockReason.EnterAnyRead;
  825. break;
  826. case EnterLockType.Write:
  827. waiterSignaledState = WaiterStates.WriteWaiterSignaled;
  828. enterMyLockReason = EnterSpinLockReason.EnterWrite;
  829. break;
  830. default:
  831. Debug.Assert(enterLockType == EnterLockType.UpgradeToWrite);
  832. enterMyLockReason = EnterSpinLockReason.UpgradeToWrite;
  833. break;
  834. }
  835. // It was not possible to acquire the RW lock because some other thread was holding some type of lock. The other
  836. // thread, when it releases its lock, will wake appropriate waiters. Along with resetting the wait event, clear the
  837. // waiter signaled bit for this type of waiter if applicable, to indicate that a waiter of this type is no longer
  838. // signaled.
  839. //
  840. // If the waiter signaled bit is not updated upon event reset, the following scenario would lead to deadlock:
  841. // - Thread T0 signals the write waiter event or the upgradeable read waiter event to wake a waiter
  842. // - There are no threads waiting on the event, but T1 is in WaitOnEvent() after exiting the spin lock and before
  843. // actually waiting on the event (that is, it's recorded that there is one waiter for the event). It remains in
  844. // this region for a while, in the repro case it typically gets context-switched out.
  845. // - T2 acquires the RW lock in some fashion that blocks T0 or T3 from acquiring the RW lock
  846. // - T0 or T3 fails to acquire the RW lock enough times for it to enter WaitOnEvent for the same event as T1
  847. // - T0 or T3 resets the event
  848. // - T2 releases the RW lock and does not wake a waiter because the reset at the previous step lost a signal but
  849. // _waiterStates was not updated to reflect that
  850. // - T1 and other threads begin waiting on the event, but there's no longer any thread that would wake them
  851. if (waiterSignaledState != WaiterStates.None && (_waiterStates & waiterSignaledState) != WaiterStates.None)
  852. {
  853. _waiterStates &= ~waiterSignaledState;
  854. }
  855. waitEvent.Reset();
  856. numWaiters++;
  857. HasNoWaiters = false;
  858. // Setting these bits will prevent new readers from getting in.
  859. if (_numWriteWaiters == 1)
  860. SetWritersWaiting();
  861. if (_numWriteUpgradeWaiters == 1)
  862. SetUpgraderWaiting();
  863. bool waitSuccessful = false;
  864. _spinLock.Exit(); // Do the wait outside of any lock
  865. try
  866. {
  867. waitSuccessful = waitEvent.WaitOne(timeout.RemainingMilliseconds);
  868. }
  869. finally
  870. {
  871. _spinLock.Enter(enterMyLockReason);
  872. --numWaiters;
  873. if (waitSuccessful &&
  874. waiterSignaledState != WaiterStates.None &&
  875. (_waiterStates & waiterSignaledState) != WaiterStates.None)
  876. {
  877. // Indicate that a signaled waiter of this type has woken. Since non-read waiters are signaled to wake one
  878. // at a time, we avoid waking up more than one waiter of that type upon successive enter/exit loops until
  879. // the signaled thread actually wakes up. For example, if there are multiple write waiters and one thread is
  880. // repeatedly entering and exiting a write lock, every exit would otherwise signal a different write waiter
  881. // to wake up unnecessarily when only one woken waiter may actually succeed in entering the write lock.
  882. _waiterStates &= ~waiterSignaledState;
  883. }
  884. if (_numWriteWaiters == 0 && _numWriteUpgradeWaiters == 0 && _numUpgradeWaiters == 0 && _numReadWaiters == 0)
  885. HasNoWaiters = true;
  886. if (_numWriteWaiters == 0)
  887. ClearWritersWaiting();
  888. if (_numWriteUpgradeWaiters == 0)
  889. ClearUpgraderWaiting();
  890. if (!waitSuccessful) // We may also be about to throw for some reason. Exit myLock.
  891. {
  892. if (enterLockType >= EnterLockType.Write)
  893. {
  894. // Write waiters block read waiters from acquiring the lock. Since this was the last write waiter, try
  895. // to wake up the appropriate read waiters.
  896. ExitAndWakeUpAppropriateReadWaiters();
  897. }
  898. else
  899. {
  900. _spinLock.Exit();
  901. }
  902. }
  903. }
  904. return waitSuccessful;
  905. }
  906. /// <summary>
  907. /// Determines the appropriate events to set, leaves the locks, and sets the events.
  908. /// </summary>
  909. private void ExitAndWakeUpAppropriateWaiters()
  910. {
  911. #if DEBUG
  912. Debug.Assert(_spinLock.IsHeld);
  913. #endif
  914. if (HasNoWaiters)
  915. {
  916. _spinLock.Exit();
  917. return;
  918. }
  919. ExitAndWakeUpAppropriateWaitersPreferringWriters();
  920. }
  921. private void ExitAndWakeUpAppropriateWaitersPreferringWriters()
  922. {
  923. uint readercount = GetNumReaders();
  924. // We need this case for EU->ER->EW case, as the read count will be 2 in
  925. // that scenario.
  926. if (_fIsReentrant)
  927. {
  928. if (_numWriteUpgradeWaiters > 0 && _fUpgradeThreadHoldingRead && readercount == 2)
  929. {
  930. _spinLock.Exit(); // Exit before signaling to improve efficiency (wakee will need the lock)
  931. _waitUpgradeEvent!.Set(); // release all upgraders (however there can be at most one). Known non-null because _numWriteUpgradeWaiters > 0.
  932. return;
  933. }
  934. }
  935. if (readercount == 1 && _numWriteUpgradeWaiters > 0)
  936. {
  937. // We have to be careful now, as we are dropping the lock.
  938. // No new writes should be allowed to sneak in if an upgrade
  939. // was pending.
  940. _spinLock.Exit(); // Exit before signaling to improve efficiency (wakee will need the lock)
  941. _waitUpgradeEvent!.Set(); // release all upgraders (however there can be at most one). Known non-null because _numWriteUpgradeWaiters > 0.
  942. }
  943. else if (readercount == 0 && _numWriteWaiters > 0)
  944. {
  945. // Check if a waiter of the same type has already been signaled but hasn't woken yet. If so, avoid signaling
  946. // and waking another waiter unnecessarily.
  947. WaiterStates signaled = _waiterStates & WaiterStates.WriteWaiterSignaled;
  948. if (signaled == WaiterStates.None)
  949. {
  950. _waiterStates |= WaiterStates.WriteWaiterSignaled;
  951. }
  952. _spinLock.Exit(); // Exit before signaling to improve efficiency (wakee will need the lock)
  953. if (signaled == WaiterStates.None)
  954. {
  955. _writeEvent!.Set(); // release one writer. Known non-null because _numWriteWaiters > 0.
  956. }
  957. }
  958. else
  959. {
  960. ExitAndWakeUpAppropriateReadWaiters();
  961. }
  962. }
  963. private void ExitAndWakeUpAppropriateReadWaiters()
  964. {
  965. #if DEBUG
  966. Debug.Assert(_spinLock.IsHeld);
  967. #endif
  968. if (_numWriteWaiters != 0 || _numWriteUpgradeWaiters != 0 || HasNoWaiters)
  969. {
  970. _spinLock.Exit();
  971. return;
  972. }
  973. Debug.Assert(_numReadWaiters != 0 || _numUpgradeWaiters != 0);
  974. bool setReadEvent = _numReadWaiters != 0;
  975. bool setUpgradeEvent = _numUpgradeWaiters != 0 && _upgradeLockOwnerId == -1;
  976. if (setUpgradeEvent)
  977. {
  978. // Check if a waiter of the same type has already been signaled but hasn't woken yet. If so, avoid signaling
  979. // and waking another waiter unnecessarily.
  980. if ((_waiterStates & WaiterStates.UpgradeableReadWaiterSignaled) == WaiterStates.None)
  981. {
  982. _waiterStates |= WaiterStates.UpgradeableReadWaiterSignaled;
  983. }
  984. else
  985. {
  986. setUpgradeEvent = false;
  987. }
  988. }
  989. _spinLock.Exit(); // Exit before signaling to improve efficiency (wakee will need the lock)
  990. if (setReadEvent)
  991. _readEvent!.Set(); // release all readers. Known non-null because _numUpgradeWaiters != 0.
  992. if (setUpgradeEvent)
  993. _upgradeEvent!.Set(); // release one upgrader.
  994. }
  995. private bool IsWriterAcquired()
  996. {
  997. return (_owners & ~WAITING_WRITERS) == 0;
  998. }
  999. private void SetWriterAcquired()
  1000. {
  1001. _owners |= WRITER_HELD; // indicate we have a writer.
  1002. }
  1003. private void ClearWriterAcquired()
  1004. {
  1005. _owners &= ~WRITER_HELD;
  1006. }
  1007. private void SetWritersWaiting()
  1008. {
  1009. _owners |= WAITING_WRITERS;
  1010. }
  1011. private void ClearWritersWaiting()
  1012. {
  1013. _owners &= ~WAITING_WRITERS;
  1014. }
  1015. private void SetUpgraderWaiting()
  1016. {
  1017. _owners |= WAITING_UPGRADER;
  1018. }
  1019. private void ClearUpgraderWaiting()
  1020. {
  1021. _owners &= ~WAITING_UPGRADER;
  1022. }
  1023. private uint GetNumReaders()
  1024. {
  1025. return _owners & READER_MASK;
  1026. }
  1027. private bool ShouldSpinForEnterAnyRead()
  1028. {
  1029. // If there is a write waiter or write upgrade waiter, the waiter would block a reader from acquiring the RW lock
  1030. // because the waiter takes precedence. In that case, the reader is not likely to make progress by spinning.
  1031. // Although another thread holding a write lock would prevent this thread from acquiring a read lock, it is by
  1032. // itself not a good enough reason to skip spinning.
  1033. return HasNoWaiters || (_numWriteWaiters == 0 && _numWriteUpgradeWaiters == 0);
  1034. }
  1035. private bool ShouldSpinForEnterAnyWrite(bool isUpgradeToWrite)
  1036. {
  1037. // If there is a write upgrade waiter, the waiter would block a writer from acquiring the RW lock because the waiter
  1038. // holds a read lock. In that case, the writer is not likely to make progress by spinning. Regarding upgrading to a
  1039. // write lock, there is no type of waiter that would block the upgrade from happening. Although another thread
  1040. // holding a read or write lock would prevent this thread from acquiring the write lock, it is by itself not a good
  1041. // enough reason to skip spinning.
  1042. return isUpgradeToWrite || _numWriteUpgradeWaiters == 0;
  1043. }
  1044. private static void SpinWait(int spinCount)
  1045. {
  1046. const int LockSpinCycles = 20;
  1047. // Exponential back-off
  1048. if ((spinCount < 5) && (Environment.ProcessorCount > 1))
  1049. {
  1050. Thread.SpinWait(LockSpinCycles * spinCount);
  1051. }
  1052. else
  1053. {
  1054. Thread.Sleep(0);
  1055. }
  1056. // Don't want to Sleep(1) in this spin wait:
  1057. // - Don't want to spin for that long, since a proper wait will follow when the spin wait fails. The artificial
  1058. // delay introduced by Sleep(1) will in some cases be much longer than desired.
  1059. // - Sleep(1) would put the thread into a wait state, and a proper wait will follow when the spin wait fails
  1060. // anyway, so it's preferable to put the thread into the proper wait state
  1061. }
  1062. public void Dispose()
  1063. {
  1064. Dispose(true);
  1065. }
  1066. private void Dispose(bool disposing)
  1067. {
  1068. if (disposing && !_fDisposed)
  1069. {
  1070. if (WaitingReadCount > 0 || WaitingUpgradeCount > 0 || WaitingWriteCount > 0)
  1071. throw new SynchronizationLockException(SR.SynchronizationLockException_IncorrectDispose);
  1072. if (IsReadLockHeld || IsUpgradeableReadLockHeld || IsWriteLockHeld)
  1073. throw new SynchronizationLockException(SR.SynchronizationLockException_IncorrectDispose);
  1074. if (_writeEvent != null)
  1075. {
  1076. _writeEvent.Dispose();
  1077. _writeEvent = null;
  1078. }
  1079. if (_readEvent != null)
  1080. {
  1081. _readEvent.Dispose();
  1082. _readEvent = null;
  1083. }
  1084. if (_upgradeEvent != null)
  1085. {
  1086. _upgradeEvent.Dispose();
  1087. _upgradeEvent = null;
  1088. }
  1089. if (_waitUpgradeEvent != null)
  1090. {
  1091. _waitUpgradeEvent.Dispose();
  1092. _waitUpgradeEvent = null;
  1093. }
  1094. _fDisposed = true;
  1095. }
  1096. }
  1097. public bool IsReadLockHeld
  1098. {
  1099. get
  1100. {
  1101. if (RecursiveReadCount > 0)
  1102. return true;
  1103. else
  1104. return false;
  1105. }
  1106. }
  1107. public bool IsUpgradeableReadLockHeld
  1108. {
  1109. get
  1110. {
  1111. if (RecursiveUpgradeCount > 0)
  1112. return true;
  1113. else
  1114. return false;
  1115. }
  1116. }
  1117. public bool IsWriteLockHeld
  1118. {
  1119. get
  1120. {
  1121. if (RecursiveWriteCount > 0)
  1122. return true;
  1123. else
  1124. return false;
  1125. }
  1126. }
  1127. public LockRecursionPolicy RecursionPolicy
  1128. {
  1129. get
  1130. {
  1131. if (_fIsReentrant)
  1132. {
  1133. return LockRecursionPolicy.SupportsRecursion;
  1134. }
  1135. else
  1136. {
  1137. return LockRecursionPolicy.NoRecursion;
  1138. }
  1139. }
  1140. }
  1141. public int CurrentReadCount
  1142. {
  1143. get
  1144. {
  1145. int numreaders = (int)GetNumReaders();
  1146. if (_upgradeLockOwnerId != -1)
  1147. return numreaders - 1;
  1148. else
  1149. return numreaders;
  1150. }
  1151. }
  1152. public int RecursiveReadCount
  1153. {
  1154. get
  1155. {
  1156. int count = 0;
  1157. ReaderWriterCount? lrwc = GetThreadRWCount(dontAllocate: true);
  1158. if (lrwc != null)
  1159. count = lrwc.readercount;
  1160. return count;
  1161. }
  1162. }
  1163. public int RecursiveUpgradeCount
  1164. {
  1165. get
  1166. {
  1167. if (_fIsReentrant)
  1168. {
  1169. int count = 0;
  1170. ReaderWriterCount? lrwc = GetThreadRWCount(dontAllocate: true);
  1171. if (lrwc != null)
  1172. count = lrwc.upgradecount;
  1173. return count;
  1174. }
  1175. else
  1176. {
  1177. if (Environment.CurrentManagedThreadId == _upgradeLockOwnerId)
  1178. return 1;
  1179. else
  1180. return 0;
  1181. }
  1182. }
  1183. }
  1184. public int RecursiveWriteCount
  1185. {
  1186. get
  1187. {
  1188. if (_fIsReentrant)
  1189. {
  1190. int count = 0;
  1191. ReaderWriterCount? lrwc = GetThreadRWCount(dontAllocate: true);
  1192. if (lrwc != null)
  1193. count = lrwc.writercount;
  1194. return count;
  1195. }
  1196. else
  1197. {
  1198. if (Environment.CurrentManagedThreadId == _writeLockOwnerId)
  1199. return 1;
  1200. else
  1201. return 0;
  1202. }
  1203. }
  1204. }
  1205. public int WaitingReadCount => (int)_numReadWaiters;
  1206. public int WaitingUpgradeCount => (int)_numUpgradeWaiters;
  1207. public int WaitingWriteCount => (int)_numWriteWaiters;
  1208. private struct SpinLock
  1209. {
  1210. private int _isLocked;
  1211. /// <summary>
  1212. /// Used to deprioritize threads attempting to enter the lock when they would not make progress after doing so.
  1213. /// <see cref="EnterSpin(EnterSpinLockReason)"/> avoids acquiring the lock as long as the operation for which it
  1214. /// was called is deprioritized.
  1215. ///
  1216. /// Layout:
  1217. /// - Low 16 bits: Number of threads that have deprioritized an enter-any-write operation
  1218. /// - High 16 bits: Number of threads that have deprioritized an enter-any-read operation
  1219. /// </summary>
  1220. private int _enterDeprioritizationState;
  1221. // Layout-specific constants for _enterDeprioritizationState
  1222. private const int DeprioritizeEnterAnyReadIncrement = 1 << 16;
  1223. private const int DeprioritizeEnterAnyWriteIncrement = 1;
  1224. // The variables controlling spinning behavior of this spin lock
  1225. private const int LockSpinCycles = 20;
  1226. private const int LockSpinCount = 10;
  1227. private const int LockSleep0Count = 5;
  1228. private const int DeprioritizedLockSleep1Count = 5;
  1229. private static int GetEnterDeprioritizationStateChange(EnterSpinLockReason reason)
  1230. {
  1231. EnterSpinLockReason operation = reason & EnterSpinLockReason.OperationMask;
  1232. switch (operation)
  1233. {
  1234. case EnterSpinLockReason.EnterAnyRead:
  1235. return 0;
  1236. case EnterSpinLockReason.ExitAnyRead:
  1237. // A read lock is held until this thread is able to exit it, so deprioritize enter-write threads as they
  1238. // will not be able to make progress
  1239. return DeprioritizeEnterAnyWriteIncrement;
  1240. case EnterSpinLockReason.EnterWrite:
  1241. // Writers are typically much less frequent and much less in number than readers. Waiting writers take
  1242. // precedence over new read attempts in order to let current readers release their lock and allow a
  1243. // writer to obtain the lock. Before a writer can register as a waiter though, the presence of just
  1244. // relatively few enter-read spins can easily starve the enter-write from even entering this lock,
  1245. // delaying its spin loop for an unreasonable duration.
  1246. //
  1247. // Deprioritize enter-read to preference enter-write. This makes it easier for enter-write threads to
  1248. // starve enter-read threads. However, writers can already by design starve readers. A waiting writer
  1249. // blocks enter-read threads and a new enter-write that needs to wait will be given precedence over
  1250. // previously waiting enter-read threads. So this is not a new problem, and the RW lock is designed for
  1251. // scenarios where writers are rare compared to readers.
  1252. return DeprioritizeEnterAnyReadIncrement;
  1253. default:
  1254. Debug.Assert(
  1255. operation == EnterSpinLockReason.UpgradeToWrite ||
  1256. operation == EnterSpinLockReason.EnterRecursiveWrite ||
  1257. operation == EnterSpinLockReason.ExitAnyWrite);
  1258. // UpgradeToWrite:
  1259. // - A read lock is held and an exit-read is not nearby, so deprioritize enter-write threads as they
  1260. // will not be able to make progress. This thread also intends to enter a write lock, so deprioritize
  1261. // enter -read threads as well, see case EnterSpinLockReason.EnterWrite for the rationale.
  1262. // EnterRecursiveWrite, ExitAnyWrite:
  1263. // - In both cases, a write lock is held until this thread is able to exit it, so deprioritize
  1264. // enter -read and enter-write threads as they will not be able to make progress
  1265. return DeprioritizeEnterAnyReadIncrement + DeprioritizeEnterAnyWriteIncrement;
  1266. }
  1267. }
  1268. private ushort EnterForEnterAnyReadDeprioritizedCount
  1269. {
  1270. get
  1271. {
  1272. Debug.Assert(DeprioritizeEnterAnyReadIncrement == (1 << 16));
  1273. return (ushort)((uint)_enterDeprioritizationState >> 16);
  1274. }
  1275. }
  1276. private ushort EnterForEnterAnyWriteDeprioritizedCount
  1277. {
  1278. get
  1279. {
  1280. Debug.Assert(DeprioritizeEnterAnyWriteIncrement == 1);
  1281. return (ushort)_enterDeprioritizationState;
  1282. }
  1283. }
  1284. private bool IsEnterDeprioritized(EnterSpinLockReason reason)
  1285. {
  1286. Debug.Assert((reason & EnterSpinLockReason.Wait) != 0 || reason == (reason & EnterSpinLockReason.OperationMask));
  1287. Debug.Assert(
  1288. (reason & EnterSpinLockReason.Wait) == 0 ||
  1289. (reason & EnterSpinLockReason.OperationMask) == EnterSpinLockReason.EnterAnyRead ||
  1290. (reason & EnterSpinLockReason.OperationMask) == EnterSpinLockReason.EnterWrite ||
  1291. (reason & EnterSpinLockReason.OperationMask) == EnterSpinLockReason.UpgradeToWrite);
  1292. switch (reason)
  1293. {
  1294. default:
  1295. Debug.Assert(
  1296. (reason & EnterSpinLockReason.Wait) != 0 ||
  1297. reason == EnterSpinLockReason.ExitAnyRead ||
  1298. reason == EnterSpinLockReason.EnterRecursiveWrite ||
  1299. reason == EnterSpinLockReason.ExitAnyWrite);
  1300. return false;
  1301. case EnterSpinLockReason.EnterAnyRead:
  1302. return EnterForEnterAnyReadDeprioritizedCount != 0;
  1303. case EnterSpinLockReason.EnterWrite:
  1304. Debug.Assert((GetEnterDeprioritizationStateChange(reason) & DeprioritizeEnterAnyWriteIncrement) == 0);
  1305. return EnterForEnterAnyWriteDeprioritizedCount != 0;
  1306. case EnterSpinLockReason.UpgradeToWrite:
  1307. Debug.Assert((GetEnterDeprioritizationStateChange(reason) & DeprioritizeEnterAnyWriteIncrement) != 0);
  1308. return EnterForEnterAnyWriteDeprioritizedCount > 1;
  1309. }
  1310. }
  1311. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  1312. private bool TryEnter()
  1313. {
  1314. return Interlocked.CompareExchange(ref _isLocked, 1, 0) == 0;
  1315. }
  1316. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  1317. public void Enter(EnterSpinLockReason reason)
  1318. {
  1319. if (!TryEnter())
  1320. {
  1321. EnterSpin(reason);
  1322. }
  1323. }
  1324. private void EnterSpin(EnterSpinLockReason reason)
  1325. {
  1326. int deprioritizationStateChange = GetEnterDeprioritizationStateChange(reason);
  1327. if (deprioritizationStateChange != 0)
  1328. {
  1329. Interlocked.Add(ref _enterDeprioritizationState, deprioritizationStateChange);
  1330. }
  1331. int processorCount = Environment.ProcessorCount;
  1332. for (int spinIndex = 0; ; spinIndex++)
  1333. {
  1334. if (spinIndex < LockSpinCount && processorCount > 1)
  1335. {
  1336. Thread.SpinWait(LockSpinCycles * (spinIndex + 1)); // Wait a few dozen instructions to let another processor release lock.
  1337. }
  1338. else if (spinIndex < (LockSpinCount + LockSleep0Count))
  1339. {
  1340. Thread.Sleep(0); // Give up my quantum.
  1341. }
  1342. else
  1343. {
  1344. Thread.Sleep(1); // Give up my quantum.
  1345. }
  1346. if (!IsEnterDeprioritized(reason))
  1347. {
  1348. if (_isLocked == 0 && TryEnter())
  1349. {
  1350. if (deprioritizationStateChange != 0)
  1351. {
  1352. Interlocked.Add(ref _enterDeprioritizationState, -deprioritizationStateChange);
  1353. }
  1354. return;
  1355. }
  1356. continue;
  1357. }
  1358. // It's possible for an Enter thread to be deprioritized for an extended duration. It's undesirable for a
  1359. // deprioritized thread to keep waking up to spin despite a Sleep(1) when a large number of such threads are
  1360. // involved. After a threshold of Sleep(1)s, ignore the deprioritization and enter this lock to allow this
  1361. // thread to stop spinning and hopefully enter a proper wait state.
  1362. Debug.Assert(
  1363. reason == EnterSpinLockReason.EnterAnyRead ||
  1364. reason == EnterSpinLockReason.EnterWrite ||
  1365. reason == EnterSpinLockReason.UpgradeToWrite);
  1366. if (spinIndex >= (LockSpinCount + LockSleep0Count + DeprioritizedLockSleep1Count))
  1367. {
  1368. reason |= EnterSpinLockReason.Wait;
  1369. spinIndex = -1;
  1370. }
  1371. }
  1372. }
  1373. public void Exit()
  1374. {
  1375. Debug.Assert(_isLocked != 0, "Exiting spin lock that is not held");
  1376. Volatile.Write(ref _isLocked, 0);
  1377. }
  1378. #if DEBUG
  1379. public bool IsHeld => _isLocked != 0;
  1380. #endif
  1381. }
  1382. [Flags]
  1383. private enum WaiterStates : byte
  1384. {
  1385. None = 0x0,
  1386. // Used for quick check when there are no waiters
  1387. NoWaiters = 0x1,
  1388. // Used to avoid signaling more than one waiter to wake up when only one can make progress, see WaitOnEvent
  1389. WriteWaiterSignaled = 0x2,
  1390. UpgradeableReadWaiterSignaled = 0x4
  1391. // Write upgrade waiters are excluded because there can only be one at any given time
  1392. }
  1393. private enum EnterSpinLockReason
  1394. {
  1395. EnterAnyRead = 0,
  1396. ExitAnyRead = 1,
  1397. EnterWrite = 2,
  1398. UpgradeToWrite = 3,
  1399. EnterRecursiveWrite = 4,
  1400. ExitAnyWrite = 5,
  1401. OperationMask = 0x7,
  1402. Wait = 0x8
  1403. }
  1404. private enum EnterLockType
  1405. {
  1406. Read,
  1407. UpgradeableRead,
  1408. Write,
  1409. UpgradeToWrite
  1410. }
  1411. }
  1412. }