ReaderWriterLockSlim.cs 61 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 Internal.Runtime.Augments;
  5. using System.Diagnostics; // for TraceInformation
  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 = null;
  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(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(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(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(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(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(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(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(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. if (IsRwHashEntryChanged(lrwc))
  537. lrwc = GetThreadRWCount(false);
  538. lrwc.writercount++;
  539. }
  540. _spinLock.Exit();
  541. _writeLockOwnerId = id;
  542. return true;
  543. }
  544. public void EnterUpgradeableReadLock()
  545. {
  546. TryEnterUpgradeableReadLock(-1);
  547. }
  548. public bool TryEnterUpgradeableReadLock(TimeSpan timeout)
  549. {
  550. return TryEnterUpgradeableReadLock(new TimeoutTracker(timeout));
  551. }
  552. public bool TryEnterUpgradeableReadLock(int millisecondsTimeout)
  553. {
  554. return TryEnterUpgradeableReadLock(new TimeoutTracker(millisecondsTimeout));
  555. }
  556. private bool TryEnterUpgradeableReadLock(TimeoutTracker timeout)
  557. {
  558. return TryEnterUpgradeableReadLockCore(timeout);
  559. }
  560. private bool TryEnterUpgradeableReadLockCore(TimeoutTracker timeout)
  561. {
  562. if (_fDisposed)
  563. throw new ObjectDisposedException(null);
  564. int id = Environment.CurrentManagedThreadId;
  565. ReaderWriterCount lrwc;
  566. if (!_fIsReentrant)
  567. {
  568. if (id == _upgradeLockOwnerId)
  569. {
  570. //Check for AU->AU
  571. throw new LockRecursionException(SR.LockRecursionException_RecursiveUpgradeNotAllowed);
  572. }
  573. else if (id == _writeLockOwnerId)
  574. {
  575. //Check for AU->AW
  576. throw new LockRecursionException(SR.LockRecursionException_UpgradeAfterWriteNotAllowed);
  577. }
  578. _spinLock.Enter(EnterSpinLockReason.EnterAnyRead);
  579. lrwc = GetThreadRWCount(true);
  580. //Can't acquire upgrade lock with reader lock held.
  581. if (lrwc != null && lrwc.readercount > 0)
  582. {
  583. _spinLock.Exit();
  584. throw new LockRecursionException(SR.LockRecursionException_UpgradeAfterReadNotAllowed);
  585. }
  586. }
  587. else
  588. {
  589. _spinLock.Enter(EnterSpinLockReason.EnterAnyRead);
  590. lrwc = GetThreadRWCount(false);
  591. if (id == _upgradeLockOwnerId)
  592. {
  593. lrwc.upgradecount++;
  594. _spinLock.Exit();
  595. return true;
  596. }
  597. else if (id == _writeLockOwnerId)
  598. {
  599. //Write lock is already held, Just update the global state
  600. //to show presence of upgrader.
  601. Debug.Assert((_owners & WRITER_HELD) > 0);
  602. _owners++;
  603. _upgradeLockOwnerId = id;
  604. lrwc.upgradecount++;
  605. if (lrwc.readercount > 0)
  606. _fUpgradeThreadHoldingRead = true;
  607. _spinLock.Exit();
  608. return true;
  609. }
  610. else if (lrwc.readercount > 0)
  611. {
  612. //Upgrade locks may not be acquired if only read locks have been
  613. //acquired.
  614. _spinLock.Exit();
  615. throw new LockRecursionException(SR.LockRecursionException_UpgradeAfterReadNotAllowed);
  616. }
  617. }
  618. bool retVal = true;
  619. int spinCount = 0;
  620. for (; ;)
  621. {
  622. //Once an upgrade lock is taken, it's like having a reader lock held
  623. //until upgrade or downgrade operations are performed.
  624. if ((_upgradeLockOwnerId == -1) && (_owners < MAX_READER))
  625. {
  626. _owners++;
  627. _upgradeLockOwnerId = id;
  628. break;
  629. }
  630. if (timeout.IsExpired)
  631. {
  632. _spinLock.Exit();
  633. return false;
  634. }
  635. if (spinCount < MaxSpinCount && ShouldSpinForEnterAnyRead())
  636. {
  637. _spinLock.Exit();
  638. spinCount++;
  639. SpinWait(spinCount);
  640. _spinLock.Enter(EnterSpinLockReason.EnterAnyRead);
  641. continue;
  642. }
  643. // Drat, we need to wait. Mark that we have waiters and wait.
  644. if (_upgradeEvent == null) // Create the needed event
  645. {
  646. LazyCreateEvent(ref _upgradeEvent, EnterLockType.UpgradeableRead);
  647. continue; // since we left the lock, start over.
  648. }
  649. //Only one thread with the upgrade lock held can proceed.
  650. retVal = WaitOnEvent(_upgradeEvent, ref _numUpgradeWaiters, timeout, EnterLockType.UpgradeableRead);
  651. if (!retVal)
  652. return false;
  653. }
  654. if (_fIsReentrant)
  655. {
  656. //The lock may have been dropped getting here, so make a quick check to see whether some other
  657. //thread did not grab the entry.
  658. if (IsRwHashEntryChanged(lrwc))
  659. lrwc = GetThreadRWCount(false);
  660. lrwc.upgradecount++;
  661. }
  662. _spinLock.Exit();
  663. return true;
  664. }
  665. public void ExitReadLock()
  666. {
  667. ReaderWriterCount lrwc = null;
  668. _spinLock.Enter(EnterSpinLockReason.ExitAnyRead);
  669. lrwc = GetThreadRWCount(true);
  670. if (lrwc == null || lrwc.readercount < 1)
  671. {
  672. //You have to be holding the read lock to make this call.
  673. _spinLock.Exit();
  674. throw new SynchronizationLockException(SR.SynchronizationLockException_MisMatchedRead);
  675. }
  676. if (_fIsReentrant)
  677. {
  678. if (lrwc.readercount > 1)
  679. {
  680. lrwc.readercount--;
  681. _spinLock.Exit();
  682. return;
  683. }
  684. if (Environment.CurrentManagedThreadId == _upgradeLockOwnerId)
  685. {
  686. _fUpgradeThreadHoldingRead = false;
  687. }
  688. }
  689. Debug.Assert(_owners > 0, "ReleasingReaderLock: releasing lock and no read lock taken");
  690. --_owners;
  691. Debug.Assert(lrwc.readercount == 1);
  692. lrwc.readercount--;
  693. ExitAndWakeUpAppropriateWaiters();
  694. }
  695. public void ExitWriteLock()
  696. {
  697. ReaderWriterCount lrwc;
  698. if (!_fIsReentrant)
  699. {
  700. if (Environment.CurrentManagedThreadId != _writeLockOwnerId)
  701. {
  702. //You have to be holding the write lock to make this call.
  703. throw new SynchronizationLockException(SR.SynchronizationLockException_MisMatchedWrite);
  704. }
  705. _spinLock.Enter(EnterSpinLockReason.ExitAnyWrite);
  706. }
  707. else
  708. {
  709. _spinLock.Enter(EnterSpinLockReason.ExitAnyWrite);
  710. lrwc = GetThreadRWCount(false);
  711. if (lrwc == null)
  712. {
  713. _spinLock.Exit();
  714. throw new SynchronizationLockException(SR.SynchronizationLockException_MisMatchedWrite);
  715. }
  716. if (lrwc.writercount < 1)
  717. {
  718. _spinLock.Exit();
  719. throw new SynchronizationLockException(SR.SynchronizationLockException_MisMatchedWrite);
  720. }
  721. lrwc.writercount--;
  722. if (lrwc.writercount > 0)
  723. {
  724. _spinLock.Exit();
  725. return;
  726. }
  727. }
  728. Debug.Assert((_owners & WRITER_HELD) > 0, "Calling ReleaseWriterLock when no write lock is held");
  729. ClearWriterAcquired();
  730. _writeLockOwnerId = -1;
  731. ExitAndWakeUpAppropriateWaiters();
  732. }
  733. public void ExitUpgradeableReadLock()
  734. {
  735. ReaderWriterCount lrwc;
  736. if (!_fIsReentrant)
  737. {
  738. if (Environment.CurrentManagedThreadId != _upgradeLockOwnerId)
  739. {
  740. //You have to be holding the upgrade lock to make this call.
  741. throw new SynchronizationLockException(SR.SynchronizationLockException_MisMatchedUpgrade);
  742. }
  743. _spinLock.Enter(EnterSpinLockReason.ExitAnyRead);
  744. }
  745. else
  746. {
  747. _spinLock.Enter(EnterSpinLockReason.ExitAnyRead);
  748. lrwc = GetThreadRWCount(true);
  749. if (lrwc == null)
  750. {
  751. _spinLock.Exit();
  752. throw new SynchronizationLockException(SR.SynchronizationLockException_MisMatchedUpgrade);
  753. }
  754. if (lrwc.upgradecount < 1)
  755. {
  756. _spinLock.Exit();
  757. throw new SynchronizationLockException(SR.SynchronizationLockException_MisMatchedUpgrade);
  758. }
  759. lrwc.upgradecount--;
  760. if (lrwc.upgradecount > 0)
  761. {
  762. _spinLock.Exit();
  763. return;
  764. }
  765. _fUpgradeThreadHoldingRead = false;
  766. }
  767. _owners--;
  768. _upgradeLockOwnerId = -1;
  769. ExitAndWakeUpAppropriateWaiters();
  770. }
  771. /// <summary>
  772. /// A routine for lazily creating a event outside the lock (so if errors
  773. /// happen they are outside the lock and that we don't do much work
  774. /// while holding a spin lock). If all goes well, reenter the lock and
  775. /// set 'waitEvent'
  776. /// </summary>
  777. private void LazyCreateEvent(ref EventWaitHandle waitEvent, EnterLockType enterLockType)
  778. {
  779. #if DEBUG
  780. Debug.Assert(_spinLock.IsHeld);
  781. Debug.Assert(waitEvent == null);
  782. #endif
  783. _spinLock.Exit();
  784. var newEvent =
  785. new EventWaitHandle(
  786. false,
  787. enterLockType == EnterLockType.Read ? EventResetMode.ManualReset : EventResetMode.AutoReset);
  788. EnterSpinLockReason enterMyLockReason;
  789. switch (enterLockType)
  790. {
  791. case EnterLockType.Read:
  792. case EnterLockType.UpgradeableRead:
  793. enterMyLockReason = EnterSpinLockReason.EnterAnyRead | EnterSpinLockReason.Wait;
  794. break;
  795. case EnterLockType.Write:
  796. enterMyLockReason = EnterSpinLockReason.EnterWrite | EnterSpinLockReason.Wait;
  797. break;
  798. default:
  799. Debug.Assert(enterLockType == EnterLockType.UpgradeToWrite);
  800. enterMyLockReason = EnterSpinLockReason.UpgradeToWrite | EnterSpinLockReason.Wait;
  801. break;
  802. }
  803. _spinLock.Enter(enterMyLockReason);
  804. if (waitEvent == null) // maybe someone snuck in.
  805. waitEvent = newEvent;
  806. else
  807. newEvent.Dispose();
  808. }
  809. /// <summary>
  810. /// Waits on 'waitEvent' with a timeout
  811. /// Before the wait 'numWaiters' is incremented and is restored before leaving this routine.
  812. /// </summary>
  813. private bool WaitOnEvent(
  814. EventWaitHandle waitEvent,
  815. ref uint numWaiters,
  816. TimeoutTracker timeout,
  817. EnterLockType enterLockType)
  818. {
  819. #if DEBUG
  820. Debug.Assert(_spinLock.IsHeld);
  821. #endif
  822. WaiterStates waiterSignaledState = WaiterStates.None;
  823. EnterSpinLockReason enterMyLockReason;
  824. switch (enterLockType)
  825. {
  826. case EnterLockType.UpgradeableRead:
  827. waiterSignaledState = WaiterStates.UpgradeableReadWaiterSignaled;
  828. goto case EnterLockType.Read;
  829. case EnterLockType.Read:
  830. enterMyLockReason = EnterSpinLockReason.EnterAnyRead;
  831. break;
  832. case EnterLockType.Write:
  833. waiterSignaledState = WaiterStates.WriteWaiterSignaled;
  834. enterMyLockReason = EnterSpinLockReason.EnterWrite;
  835. break;
  836. default:
  837. Debug.Assert(enterLockType == EnterLockType.UpgradeToWrite);
  838. enterMyLockReason = EnterSpinLockReason.UpgradeToWrite;
  839. break;
  840. }
  841. // It was not possible to acquire the RW lock because some other thread was holding some type of lock. The other
  842. // thread, when it releases its lock, will wake appropriate waiters. Along with resetting the wait event, clear the
  843. // waiter signaled bit for this type of waiter if applicable, to indicate that a waiter of this type is no longer
  844. // signaled.
  845. //
  846. // If the waiter signaled bit is not updated upon event reset, the following scenario would lead to deadlock:
  847. // - Thread T0 signals the write waiter event or the upgradeable read waiter event to wake a waiter
  848. // - There are no threads waiting on the event, but T1 is in WaitOnEvent() after exiting the spin lock and before
  849. // actually waiting on the event (that is, it's recorded that there is one waiter for the event). It remains in
  850. // this region for a while, in the repro case it typically gets context-switched out.
  851. // - T2 acquires the RW lock in some fashion that blocks T0 or T3 from acquiring the RW lock
  852. // - T0 or T3 fails to acquire the RW lock enough times for it to enter WaitOnEvent for the same event as T1
  853. // - T0 or T3 resets the event
  854. // - T2 releases the RW lock and does not wake a waiter because the reset at the previous step lost a signal but
  855. // _waiterStates was not updated to reflect that
  856. // - T1 and other threads begin waiting on the event, but there's no longer any thread that would wake them
  857. if (waiterSignaledState != WaiterStates.None && (_waiterStates & waiterSignaledState) != WaiterStates.None)
  858. {
  859. _waiterStates &= ~waiterSignaledState;
  860. }
  861. waitEvent.Reset();
  862. numWaiters++;
  863. HasNoWaiters = false;
  864. //Setting these bits will prevent new readers from getting in.
  865. if (_numWriteWaiters == 1)
  866. SetWritersWaiting();
  867. if (_numWriteUpgradeWaiters == 1)
  868. SetUpgraderWaiting();
  869. bool waitSuccessful = false;
  870. _spinLock.Exit(); // Do the wait outside of any lock
  871. try
  872. {
  873. waitSuccessful = waitEvent.WaitOne(timeout.RemainingMilliseconds);
  874. }
  875. finally
  876. {
  877. _spinLock.Enter(enterMyLockReason);
  878. --numWaiters;
  879. if (waitSuccessful &&
  880. waiterSignaledState != WaiterStates.None &&
  881. (_waiterStates & waiterSignaledState) != WaiterStates.None)
  882. {
  883. // Indicate that a signaled waiter of this type has woken. Since non-read waiters are signaled to wake one
  884. // at a time, we avoid waking up more than one waiter of that type upon successive enter/exit loops until
  885. // the signaled thread actually wakes up. For example, if there are multiple write waiters and one thread is
  886. // repeatedly entering and exiting a write lock, every exit would otherwise signal a different write waiter
  887. // to wake up unnecessarily when only one woken waiter may actually succeed in entering the write lock.
  888. _waiterStates &= ~waiterSignaledState;
  889. }
  890. if (_numWriteWaiters == 0 && _numWriteUpgradeWaiters == 0 && _numUpgradeWaiters == 0 && _numReadWaiters == 0)
  891. HasNoWaiters = true;
  892. if (_numWriteWaiters == 0)
  893. ClearWritersWaiting();
  894. if (_numWriteUpgradeWaiters == 0)
  895. ClearUpgraderWaiting();
  896. if (!waitSuccessful) // We may also be about to throw for some reason. Exit myLock.
  897. {
  898. if (enterLockType >= EnterLockType.Write)
  899. {
  900. // Write waiters block read waiters from acquiring the lock. Since this was the last write waiter, try
  901. // to wake up the appropriate read waiters.
  902. ExitAndWakeUpAppropriateReadWaiters();
  903. }
  904. else
  905. {
  906. _spinLock.Exit();
  907. }
  908. }
  909. }
  910. return waitSuccessful;
  911. }
  912. /// <summary>
  913. /// Determines the appropriate events to set, leaves the locks, and sets the events.
  914. /// </summary>
  915. private void ExitAndWakeUpAppropriateWaiters()
  916. {
  917. #if DEBUG
  918. Debug.Assert(_spinLock.IsHeld);
  919. #endif
  920. if (HasNoWaiters)
  921. {
  922. _spinLock.Exit();
  923. return;
  924. }
  925. ExitAndWakeUpAppropriateWaitersPreferringWriters();
  926. }
  927. private void ExitAndWakeUpAppropriateWaitersPreferringWriters()
  928. {
  929. uint readercount = GetNumReaders();
  930. //We need this case for EU->ER->EW case, as the read count will be 2 in
  931. //that scenario.
  932. if (_fIsReentrant)
  933. {
  934. if (_numWriteUpgradeWaiters > 0 && _fUpgradeThreadHoldingRead && readercount == 2)
  935. {
  936. _spinLock.Exit(); // Exit before signaling to improve efficiency (wakee will need the lock)
  937. _waitUpgradeEvent.Set(); // release all upgraders (however there can be at most one).
  938. return;
  939. }
  940. }
  941. if (readercount == 1 && _numWriteUpgradeWaiters > 0)
  942. {
  943. //We have to be careful now, as we are dropping the lock.
  944. //No new writes should be allowed to sneak in if an upgrade
  945. //was pending.
  946. _spinLock.Exit(); // Exit before signaling to improve efficiency (wakee will need the lock)
  947. _waitUpgradeEvent.Set(); // release all upgraders (however there can be at most one).
  948. }
  949. else if (readercount == 0 && _numWriteWaiters > 0)
  950. {
  951. // Check if a waiter of the same type has already been signaled but hasn't woken yet. If so, avoid signaling
  952. // and waking another waiter unnecessarily.
  953. WaiterStates signaled = _waiterStates & WaiterStates.WriteWaiterSignaled;
  954. if (signaled == WaiterStates.None)
  955. {
  956. _waiterStates |= WaiterStates.WriteWaiterSignaled;
  957. }
  958. _spinLock.Exit(); // Exit before signaling to improve efficiency (wakee will need the lock)
  959. if (signaled == WaiterStates.None)
  960. {
  961. _writeEvent.Set(); // release one writer.
  962. }
  963. }
  964. else
  965. {
  966. ExitAndWakeUpAppropriateReadWaiters();
  967. }
  968. }
  969. private void ExitAndWakeUpAppropriateReadWaiters()
  970. {
  971. #if DEBUG
  972. Debug.Assert(_spinLock.IsHeld);
  973. #endif
  974. if (_numWriteWaiters != 0 || _numWriteUpgradeWaiters != 0 || HasNoWaiters)
  975. {
  976. _spinLock.Exit();
  977. return;
  978. }
  979. Debug.Assert(_numReadWaiters != 0 || _numUpgradeWaiters != 0);
  980. bool setReadEvent = _numReadWaiters != 0;
  981. bool setUpgradeEvent = _numUpgradeWaiters != 0 && _upgradeLockOwnerId == -1;
  982. if (setUpgradeEvent)
  983. {
  984. // Check if a waiter of the same type has already been signaled but hasn't woken yet. If so, avoid signaling
  985. // and waking another waiter unnecessarily.
  986. if ((_waiterStates & WaiterStates.UpgradeableReadWaiterSignaled) == WaiterStates.None)
  987. {
  988. _waiterStates |= WaiterStates.UpgradeableReadWaiterSignaled;
  989. }
  990. else
  991. {
  992. setUpgradeEvent = false;
  993. }
  994. }
  995. _spinLock.Exit(); // Exit before signaling to improve efficiency (wakee will need the lock)
  996. if (setReadEvent)
  997. _readEvent.Set(); // release all readers.
  998. if (setUpgradeEvent)
  999. _upgradeEvent.Set(); //release one upgrader.
  1000. }
  1001. private bool IsWriterAcquired()
  1002. {
  1003. return (_owners & ~WAITING_WRITERS) == 0;
  1004. }
  1005. private void SetWriterAcquired()
  1006. {
  1007. _owners |= WRITER_HELD; // indicate we have a writer.
  1008. }
  1009. private void ClearWriterAcquired()
  1010. {
  1011. _owners &= ~WRITER_HELD;
  1012. }
  1013. private void SetWritersWaiting()
  1014. {
  1015. _owners |= WAITING_WRITERS;
  1016. }
  1017. private void ClearWritersWaiting()
  1018. {
  1019. _owners &= ~WAITING_WRITERS;
  1020. }
  1021. private void SetUpgraderWaiting()
  1022. {
  1023. _owners |= WAITING_UPGRADER;
  1024. }
  1025. private void ClearUpgraderWaiting()
  1026. {
  1027. _owners &= ~WAITING_UPGRADER;
  1028. }
  1029. private uint GetNumReaders()
  1030. {
  1031. return _owners & READER_MASK;
  1032. }
  1033. private bool ShouldSpinForEnterAnyRead()
  1034. {
  1035. // If there is a write waiter or write upgrade waiter, the waiter would block a reader from acquiring the RW lock
  1036. // because the waiter takes precedence. In that case, the reader is not likely to make progress by spinning.
  1037. // Although another thread holding a write lock would prevent this thread from acquiring a read lock, it is by
  1038. // itself not a good enough reason to skip spinning.
  1039. return HasNoWaiters || (_numWriteWaiters == 0 && _numWriteUpgradeWaiters == 0);
  1040. }
  1041. private bool ShouldSpinForEnterAnyWrite(bool isUpgradeToWrite)
  1042. {
  1043. // If there is a write upgrade waiter, the waiter would block a writer from acquiring the RW lock because the waiter
  1044. // holds a read lock. In that case, the writer is not likely to make progress by spinning. Regarding upgrading to a
  1045. // write lock, there is no type of waiter that would block the upgrade from happening. Although another thread
  1046. // holding a read or write lock would prevent this thread from acquiring the write lock, it is by itself not a good
  1047. // enough reason to skip spinning.
  1048. return isUpgradeToWrite || _numWriteUpgradeWaiters == 0;
  1049. }
  1050. private static void SpinWait(int spinCount)
  1051. {
  1052. const int LockSpinCycles = 20;
  1053. //Exponential back-off
  1054. if ((spinCount < 5) && (ProcessorCount > 1))
  1055. {
  1056. RuntimeThread.SpinWait(LockSpinCycles * spinCount);
  1057. }
  1058. else
  1059. {
  1060. RuntimeThread.Sleep(0);
  1061. }
  1062. // Don't want to Sleep(1) in this spin wait:
  1063. // - Don't want to spin for that long, since a proper wait will follow when the spin wait fails. The artificial
  1064. // delay introduced by Sleep(1) will in some cases be much longer than desired.
  1065. // - Sleep(1) would put the thread into a wait state, and a proper wait will follow when the spin wait fails
  1066. // anyway, so it's preferable to put the thread into the proper wait state
  1067. }
  1068. public void Dispose()
  1069. {
  1070. Dispose(true);
  1071. }
  1072. private void Dispose(bool disposing)
  1073. {
  1074. if (disposing && !_fDisposed)
  1075. {
  1076. if (WaitingReadCount > 0 || WaitingUpgradeCount > 0 || WaitingWriteCount > 0)
  1077. throw new SynchronizationLockException(SR.SynchronizationLockException_IncorrectDispose);
  1078. if (IsReadLockHeld || IsUpgradeableReadLockHeld || IsWriteLockHeld)
  1079. throw new SynchronizationLockException(SR.SynchronizationLockException_IncorrectDispose);
  1080. if (_writeEvent != null)
  1081. {
  1082. _writeEvent.Dispose();
  1083. _writeEvent = null;
  1084. }
  1085. if (_readEvent != null)
  1086. {
  1087. _readEvent.Dispose();
  1088. _readEvent = null;
  1089. }
  1090. if (_upgradeEvent != null)
  1091. {
  1092. _upgradeEvent.Dispose();
  1093. _upgradeEvent = null;
  1094. }
  1095. if (_waitUpgradeEvent != null)
  1096. {
  1097. _waitUpgradeEvent.Dispose();
  1098. _waitUpgradeEvent = null;
  1099. }
  1100. _fDisposed = true;
  1101. }
  1102. }
  1103. public bool IsReadLockHeld
  1104. {
  1105. get
  1106. {
  1107. if (RecursiveReadCount > 0)
  1108. return true;
  1109. else
  1110. return false;
  1111. }
  1112. }
  1113. public bool IsUpgradeableReadLockHeld
  1114. {
  1115. get
  1116. {
  1117. if (RecursiveUpgradeCount > 0)
  1118. return true;
  1119. else
  1120. return false;
  1121. }
  1122. }
  1123. public bool IsWriteLockHeld
  1124. {
  1125. get
  1126. {
  1127. if (RecursiveWriteCount > 0)
  1128. return true;
  1129. else
  1130. return false;
  1131. }
  1132. }
  1133. public LockRecursionPolicy RecursionPolicy
  1134. {
  1135. get
  1136. {
  1137. if (_fIsReentrant)
  1138. {
  1139. return LockRecursionPolicy.SupportsRecursion;
  1140. }
  1141. else
  1142. {
  1143. return LockRecursionPolicy.NoRecursion;
  1144. }
  1145. }
  1146. }
  1147. public int CurrentReadCount
  1148. {
  1149. get
  1150. {
  1151. int numreaders = (int)GetNumReaders();
  1152. if (_upgradeLockOwnerId != -1)
  1153. return numreaders - 1;
  1154. else
  1155. return numreaders;
  1156. }
  1157. }
  1158. public int RecursiveReadCount
  1159. {
  1160. get
  1161. {
  1162. int count = 0;
  1163. ReaderWriterCount lrwc = GetThreadRWCount(true);
  1164. if (lrwc != null)
  1165. count = lrwc.readercount;
  1166. return count;
  1167. }
  1168. }
  1169. public int RecursiveUpgradeCount
  1170. {
  1171. get
  1172. {
  1173. if (_fIsReentrant)
  1174. {
  1175. int count = 0;
  1176. ReaderWriterCount lrwc = GetThreadRWCount(true);
  1177. if (lrwc != null)
  1178. count = lrwc.upgradecount;
  1179. return count;
  1180. }
  1181. else
  1182. {
  1183. if (Environment.CurrentManagedThreadId == _upgradeLockOwnerId)
  1184. return 1;
  1185. else
  1186. return 0;
  1187. }
  1188. }
  1189. }
  1190. public int RecursiveWriteCount
  1191. {
  1192. get
  1193. {
  1194. if (_fIsReentrant)
  1195. {
  1196. int count = 0;
  1197. ReaderWriterCount lrwc = GetThreadRWCount(true);
  1198. if (lrwc != null)
  1199. count = lrwc.writercount;
  1200. return count;
  1201. }
  1202. else
  1203. {
  1204. if (Environment.CurrentManagedThreadId == _writeLockOwnerId)
  1205. return 1;
  1206. else
  1207. return 0;
  1208. }
  1209. }
  1210. }
  1211. public int WaitingReadCount
  1212. {
  1213. get
  1214. {
  1215. return (int)_numReadWaiters;
  1216. }
  1217. }
  1218. public int WaitingUpgradeCount
  1219. {
  1220. get
  1221. {
  1222. return (int)_numUpgradeWaiters;
  1223. }
  1224. }
  1225. public int WaitingWriteCount
  1226. {
  1227. get
  1228. {
  1229. return (int)_numWriteWaiters;
  1230. }
  1231. }
  1232. private struct SpinLock
  1233. {
  1234. private int _isLocked;
  1235. /// <summary>
  1236. /// Used to deprioritize threads attempting to enter the lock when they would not make progress after doing so.
  1237. /// <see cref="EnterSpin(EnterSpinLockReason)"/> avoids acquiring the lock as long as the operation for which it
  1238. /// was called is deprioritized.
  1239. ///
  1240. /// Layout:
  1241. /// - Low 16 bits: Number of threads that have deprioritized an enter-any-write operation
  1242. /// - High 16 bits: Number of threads that have deprioritized an enter-any-read operation
  1243. /// </summary>
  1244. private int _enterDeprioritizationState;
  1245. // Layout-specific constants for _enterDeprioritizationState
  1246. private const int DeprioritizeEnterAnyReadIncrement = 1 << 16;
  1247. private const int DeprioritizeEnterAnyWriteIncrement = 1;
  1248. // The variables controlling spinning behavior of this spin lock
  1249. private const int LockSpinCycles = 20;
  1250. private const int LockSpinCount = 10;
  1251. private const int LockSleep0Count = 5;
  1252. private const int DeprioritizedLockSleep1Count = 5;
  1253. private static int GetEnterDeprioritizationStateChange(EnterSpinLockReason reason)
  1254. {
  1255. EnterSpinLockReason operation = reason & EnterSpinLockReason.OperationMask;
  1256. switch (operation)
  1257. {
  1258. case EnterSpinLockReason.EnterAnyRead:
  1259. return 0;
  1260. case EnterSpinLockReason.ExitAnyRead:
  1261. // A read lock is held until this thread is able to exit it, so deprioritize enter-write threads as they
  1262. // will not be able to make progress
  1263. return DeprioritizeEnterAnyWriteIncrement;
  1264. case EnterSpinLockReason.EnterWrite:
  1265. // Writers are typically much less frequent and much less in number than readers. Waiting writers take
  1266. // precedence over new read attempts in order to let current readers release their lock and allow a
  1267. // writer to obtain the lock. Before a writer can register as a waiter though, the presence of just
  1268. // relatively few enter-read spins can easily starve the enter-write from even entering this lock,
  1269. // delaying its spin loop for an unreasonable duration.
  1270. //
  1271. // Deprioritize enter-read to preference enter-write. This makes it easier for enter-write threads to
  1272. // starve enter-read threads. However, writers can already by design starve readers. A waiting writer
  1273. // blocks enter-read threads and a new enter-write that needs to wait will be given precedence over
  1274. // previously waiting enter-read threads. So this is not a new problem, and the RW lock is designed for
  1275. // scenarios where writers are rare compared to readers.
  1276. return DeprioritizeEnterAnyReadIncrement;
  1277. default:
  1278. Debug.Assert(
  1279. operation == EnterSpinLockReason.UpgradeToWrite ||
  1280. operation == EnterSpinLockReason.EnterRecursiveWrite ||
  1281. operation == EnterSpinLockReason.ExitAnyWrite);
  1282. // UpgradeToWrite:
  1283. // - A read lock is held and an exit-read is not nearby, so deprioritize enter-write threads as they
  1284. // will not be able to make progress. This thread also intends to enter a write lock, so deprioritize
  1285. // enter -read threads as well, see case EnterSpinLockReason.EnterWrite for the rationale.
  1286. // EnterRecursiveWrite, ExitAnyWrite:
  1287. // - In both cases, a write lock is held until this thread is able to exit it, so deprioritize
  1288. // enter -read and enter-write threads as they will not be able to make progress
  1289. return DeprioritizeEnterAnyReadIncrement + DeprioritizeEnterAnyWriteIncrement;
  1290. }
  1291. }
  1292. private ushort EnterForEnterAnyReadDeprioritizedCount
  1293. {
  1294. get
  1295. {
  1296. Debug.Assert(DeprioritizeEnterAnyReadIncrement == (1 << 16));
  1297. return (ushort)((uint)_enterDeprioritizationState >> 16);
  1298. }
  1299. }
  1300. private ushort EnterForEnterAnyWriteDeprioritizedCount
  1301. {
  1302. get
  1303. {
  1304. Debug.Assert(DeprioritizeEnterAnyWriteIncrement == 1);
  1305. return (ushort)_enterDeprioritizationState;
  1306. }
  1307. }
  1308. private bool IsEnterDeprioritized(EnterSpinLockReason reason)
  1309. {
  1310. Debug.Assert((reason & EnterSpinLockReason.Wait) != 0 || reason == (reason & EnterSpinLockReason.OperationMask));
  1311. Debug.Assert(
  1312. (reason & EnterSpinLockReason.Wait) == 0 ||
  1313. (reason & EnterSpinLockReason.OperationMask) == EnterSpinLockReason.EnterAnyRead ||
  1314. (reason & EnterSpinLockReason.OperationMask) == EnterSpinLockReason.EnterWrite ||
  1315. (reason & EnterSpinLockReason.OperationMask) == EnterSpinLockReason.UpgradeToWrite);
  1316. switch (reason)
  1317. {
  1318. default:
  1319. Debug.Assert(
  1320. (reason & EnterSpinLockReason.Wait) != 0 ||
  1321. reason == EnterSpinLockReason.ExitAnyRead ||
  1322. reason == EnterSpinLockReason.EnterRecursiveWrite ||
  1323. reason == EnterSpinLockReason.ExitAnyWrite);
  1324. return false;
  1325. case EnterSpinLockReason.EnterAnyRead:
  1326. return EnterForEnterAnyReadDeprioritizedCount != 0;
  1327. case EnterSpinLockReason.EnterWrite:
  1328. Debug.Assert((GetEnterDeprioritizationStateChange(reason) & DeprioritizeEnterAnyWriteIncrement) == 0);
  1329. return EnterForEnterAnyWriteDeprioritizedCount != 0;
  1330. case EnterSpinLockReason.UpgradeToWrite:
  1331. Debug.Assert((GetEnterDeprioritizationStateChange(reason) & DeprioritizeEnterAnyWriteIncrement) != 0);
  1332. return EnterForEnterAnyWriteDeprioritizedCount > 1;
  1333. }
  1334. }
  1335. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  1336. private bool TryEnter()
  1337. {
  1338. return Interlocked.CompareExchange(ref _isLocked, 1, 0) == 0;
  1339. }
  1340. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  1341. public void Enter(EnterSpinLockReason reason)
  1342. {
  1343. if (!TryEnter())
  1344. {
  1345. EnterSpin(reason);
  1346. }
  1347. }
  1348. private void EnterSpin(EnterSpinLockReason reason)
  1349. {
  1350. int deprioritizationStateChange = GetEnterDeprioritizationStateChange(reason);
  1351. if (deprioritizationStateChange != 0)
  1352. {
  1353. Interlocked.Add(ref _enterDeprioritizationState, deprioritizationStateChange);
  1354. }
  1355. int processorCount = ProcessorCount;
  1356. for (int spinIndex = 0; ; spinIndex++)
  1357. {
  1358. if (spinIndex < LockSpinCount && processorCount > 1)
  1359. {
  1360. RuntimeThread.SpinWait(LockSpinCycles * (spinIndex + 1)); // Wait a few dozen instructions to let another processor release lock.
  1361. }
  1362. else if (spinIndex < (LockSpinCount + LockSleep0Count))
  1363. {
  1364. RuntimeThread.Sleep(0); // Give up my quantum.
  1365. }
  1366. else
  1367. {
  1368. RuntimeThread.Sleep(1); // Give up my quantum.
  1369. }
  1370. if (!IsEnterDeprioritized(reason))
  1371. {
  1372. if (_isLocked == 0 && TryEnter())
  1373. {
  1374. if (deprioritizationStateChange != 0)
  1375. {
  1376. Interlocked.Add(ref _enterDeprioritizationState, -deprioritizationStateChange);
  1377. }
  1378. return;
  1379. }
  1380. continue;
  1381. }
  1382. // It's possible for an Enter thread to be deprioritized for an extended duration. It's undesirable for a
  1383. // deprioritized thread to keep waking up to spin despite a Sleep(1) when a large number of such threads are
  1384. // involved. After a threshold of Sleep(1)s, ignore the deprioritization and enter this lock to allow this
  1385. // thread to stop spinning and hopefully enter a proper wait state.
  1386. Debug.Assert(
  1387. reason == EnterSpinLockReason.EnterAnyRead ||
  1388. reason == EnterSpinLockReason.EnterWrite ||
  1389. reason == EnterSpinLockReason.UpgradeToWrite);
  1390. if (spinIndex >= (LockSpinCount + LockSleep0Count + DeprioritizedLockSleep1Count))
  1391. {
  1392. reason |= EnterSpinLockReason.Wait;
  1393. spinIndex = -1;
  1394. }
  1395. }
  1396. }
  1397. public void Exit()
  1398. {
  1399. Debug.Assert(_isLocked != 0, "Exiting spin lock that is not held");
  1400. Volatile.Write(ref _isLocked, 0);
  1401. }
  1402. #if DEBUG
  1403. public bool IsHeld => _isLocked != 0;
  1404. #endif
  1405. }
  1406. [Flags]
  1407. private enum WaiterStates : byte
  1408. {
  1409. None = 0x0,
  1410. // Used for quick check when there are no waiters
  1411. NoWaiters = 0x1,
  1412. // Used to avoid signaling more than one waiter to wake up when only one can make progress, see WaitOnEvent
  1413. WriteWaiterSignaled = 0x2,
  1414. UpgradeableReadWaiterSignaled = 0x4
  1415. // Write upgrade waiters are excluded because there can only be one at any given time
  1416. }
  1417. private enum EnterSpinLockReason
  1418. {
  1419. EnterAnyRead = 0,
  1420. ExitAnyRead = 1,
  1421. EnterWrite = 2,
  1422. UpgradeToWrite = 3,
  1423. EnterRecursiveWrite = 4,
  1424. ExitAnyWrite = 5,
  1425. OperationMask = 0x7,
  1426. Wait = 0x8
  1427. }
  1428. private enum EnterLockType
  1429. {
  1430. Read,
  1431. UpgradeableRead,
  1432. Write,
  1433. UpgradeToWrite
  1434. }
  1435. }
  1436. }