ReaderWriterLockSlim.cs 62 KB

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