SpinWait.cs 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398
  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. // =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+
  5. //
  6. // Central spin logic used across the entire code-base.
  7. //
  8. // =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
  9. using System.Diagnostics;
  10. using Internal.Runtime.Augments;
  11. namespace System.Threading
  12. {
  13. // SpinWait is just a little value type that encapsulates some common spinning
  14. // logic. It ensures we always yield on single-proc machines (instead of using busy
  15. // waits), and that we work well on HT. It encapsulates a good mixture of spinning
  16. // and real yielding. It's a value type so that various areas of the engine can use
  17. // one by allocating it on the stack w/out unnecessary GC allocation overhead, e.g.:
  18. //
  19. // void f() {
  20. // SpinWait wait = new SpinWait();
  21. // while (!p) { wait.SpinOnce(); }
  22. // ...
  23. // }
  24. //
  25. // Internally it just maintains a counter that is used to decide when to yield, etc.
  26. //
  27. // A common usage is to spin before blocking. In those cases, the NextSpinWillYield
  28. // property allows a user to decide to fall back to waiting once it returns true:
  29. //
  30. // void f() {
  31. // SpinWait wait = new SpinWait();
  32. // while (!p) {
  33. // if (wait.NextSpinWillYield) { /* block! */ }
  34. // else { wait.SpinOnce(); }
  35. // }
  36. // ...
  37. // }
  38. /// <summary>
  39. /// Provides support for spin-based waiting.
  40. /// </summary>
  41. /// <remarks>
  42. /// <para>
  43. /// <see cref="SpinWait"/> encapsulates common spinning logic. On single-processor machines, yields are
  44. /// always used instead of busy waits, and on computers with Intel(R) processors employing Hyper-Threading
  45. /// technology, it helps to prevent hardware thread starvation. SpinWait encapsulates a good mixture of
  46. /// spinning and true yielding.
  47. /// </para>
  48. /// <para>
  49. /// <see cref="SpinWait"/> is a value type, which means that low-level code can utilize SpinWait without
  50. /// fear of unnecessary allocation overheads. SpinWait is not generally useful for ordinary applications.
  51. /// In most cases, you should use the synchronization classes provided by the .NET Framework, such as
  52. /// <see cref="System.Threading.Monitor"/>. For most purposes where spin waiting is required, however,
  53. /// the <see cref="SpinWait"/> type should be preferred over the <see
  54. /// cref="System.Threading.Thread.SpinWait"/> method.
  55. /// </para>
  56. /// <para>
  57. /// While SpinWait is designed to be used in concurrent applications, it is not designed to be
  58. /// used from multiple threads concurrently. SpinWait's members are not thread-safe. If multiple
  59. /// threads must spin, each should use its own instance of SpinWait.
  60. /// </para>
  61. /// </remarks>
  62. public struct SpinWait
  63. {
  64. // These constants determine the frequency of yields versus spinning. The
  65. // numbers may seem fairly arbitrary, but were derived with at least some
  66. // thought in the design document. I fully expect they will need to change
  67. // over time as we gain more experience with performance.
  68. internal const int YieldThreshold = 10; // When to switch over to a true yield.
  69. private const int Sleep0EveryHowManyYields = 5; // After how many yields should we Sleep(0)?
  70. internal const int DefaultSleep1Threshold = 20; // After how many yields should we Sleep(1) frequently?
  71. /// <summary>
  72. /// A suggested number of spin iterations before doing a proper wait, such as waiting on an event that becomes signaled
  73. /// when the resource becomes available.
  74. /// </summary>
  75. /// <remarks>
  76. /// These numbers were arrived at by experimenting with different numbers in various cases that currently use it. It's
  77. /// only a suggested value and typically works well when the proper wait is something like an event.
  78. ///
  79. /// Spinning less can lead to early waiting and more context switching, spinning more can decrease latency but may use
  80. /// up some CPU time unnecessarily. Depends on the situation too, for instance SemaphoreSlim uses more iterations
  81. /// because the waiting there is currently a lot more expensive (involves more spinning, taking a lock, etc.). It also
  82. /// depends on the likelihood of the spin being successful and how long the wait would be but those are not accounted
  83. /// for here.
  84. /// </remarks>
  85. internal static readonly int SpinCountforSpinBeforeWait = PlatformHelper.IsSingleProcessor ? 1 : 35;
  86. /// <summary>
  87. /// Typically, Sleep(1) should not be issued for a spin-wait before a proper wait because it is usually more beneficial
  88. /// to just issue the proper wait. For longer spin-waits (when the spin count is configurable), this value may be used as
  89. /// a threshold for issuing Sleep(1).
  90. /// </summary>
  91. /// <remarks>
  92. /// Should be greater than <see cref="SpinCountforSpinBeforeWait"/> so that Sleep(1) would not be used by default.
  93. /// </remarks>
  94. internal const int Sleep1ThresholdForLongSpinBeforeWait = 40;
  95. // The number of times we've spun already.
  96. private int _count;
  97. /// <summary>
  98. /// Gets the number of times <see cref="SpinOnce()"/> has been called on this instance.
  99. /// </summary>
  100. public int Count
  101. {
  102. get => _count;
  103. internal set
  104. {
  105. Debug.Assert(value >= 0);
  106. _count = value;
  107. }
  108. }
  109. /// <summary>
  110. /// Gets whether the next call to <see cref="SpinOnce()"/> will yield the processor, triggering a
  111. /// forced context switch.
  112. /// </summary>
  113. /// <value>Whether the next call to <see cref="SpinOnce()"/> will yield the processor, triggering a
  114. /// forced context switch.</value>
  115. /// <remarks>
  116. /// On a single-CPU machine, <see cref="SpinOnce()"/> always yields the processor. On machines with
  117. /// multiple CPUs, <see cref="SpinOnce()"/> may yield after an unspecified number of calls.
  118. /// </remarks>
  119. public bool NextSpinWillYield => _count >= YieldThreshold || PlatformHelper.IsSingleProcessor;
  120. /// <summary>
  121. /// Performs a single spin.
  122. /// </summary>
  123. /// <remarks>
  124. /// This is typically called in a loop, and may change in behavior based on the number of times a
  125. /// <see cref="SpinOnce()"/> has been called thus far on this instance.
  126. /// </remarks>
  127. public void SpinOnce()
  128. {
  129. SpinOnceCore(DefaultSleep1Threshold);
  130. }
  131. /// <summary>
  132. /// Performs a single spin.
  133. /// </summary>
  134. /// <param name="sleep1Threshold">
  135. /// A minimum spin count after which <code>Thread.Sleep(1)</code> may be used. A value of <code>-1</code> may be used to
  136. /// disable the use of <code>Thread.Sleep(1)</code>.
  137. /// </param>
  138. /// <exception cref="ArgumentOutOfRangeException">
  139. /// <paramref name="sleep1Threshold"/> is less than <code>-1</code>.
  140. /// </exception>
  141. /// <remarks>
  142. /// This is typically called in a loop, and may change in behavior based on the number of times a
  143. /// <see cref="SpinOnce()"/> has been called thus far on this instance.
  144. /// </remarks>
  145. public void SpinOnce(int sleep1Threshold)
  146. {
  147. if (sleep1Threshold < -1)
  148. {
  149. throw new ArgumentOutOfRangeException(nameof(sleep1Threshold), sleep1Threshold, SR.ArgumentOutOfRange_NeedNonNegOrNegative1);
  150. }
  151. if (sleep1Threshold >= 0 && sleep1Threshold < YieldThreshold)
  152. {
  153. sleep1Threshold = YieldThreshold;
  154. }
  155. SpinOnceCore(sleep1Threshold);
  156. }
  157. private void SpinOnceCore(int sleep1Threshold)
  158. {
  159. Debug.Assert(sleep1Threshold >= -1);
  160. Debug.Assert(sleep1Threshold < 0 || sleep1Threshold >= YieldThreshold);
  161. // (_count - YieldThreshold) % 2 == 0: The purpose of this check is to interleave Thread.Yield/Sleep(0) with
  162. // Thread.SpinWait. Otherwise, the following issues occur:
  163. // - When there are no threads to switch to, Yield and Sleep(0) become no-op and it turns the spin loop into a
  164. // busy-spin that may quickly reach the max spin count and cause the thread to enter a wait state, or may
  165. // just busy-spin for longer than desired before a Sleep(1). Completing the spin loop too early can cause
  166. // excessive context switcing if a wait follows, and entering the Sleep(1) stage too early can cause
  167. // excessive delays.
  168. // - If there are multiple threads doing Yield and Sleep(0) (typically from the same spin loop due to
  169. // contention), they may switch between one another, delaying work that can make progress.
  170. if ((
  171. _count >= YieldThreshold &&
  172. ((_count >= sleep1Threshold && sleep1Threshold >= 0) || (_count - YieldThreshold) % 2 == 0)
  173. ) ||
  174. PlatformHelper.IsSingleProcessor)
  175. {
  176. //
  177. // We must yield.
  178. //
  179. // We prefer to call Thread.Yield first, triggering a SwitchToThread. This
  180. // unfortunately doesn't consider all runnable threads on all OS SKUs. In
  181. // some cases, it may only consult the runnable threads whose ideal processor
  182. // is the one currently executing code. Thus we occasionally issue a call to
  183. // Sleep(0), which considers all runnable threads at equal priority. Even this
  184. // is insufficient since we may be spin waiting for lower priority threads to
  185. // execute; we therefore must call Sleep(1) once in a while too, which considers
  186. // all runnable threads, regardless of ideal processor and priority, but may
  187. // remove the thread from the scheduler's queue for 10+ms, if the system is
  188. // configured to use the (default) coarse-grained system timer.
  189. //
  190. if (_count >= sleep1Threshold && sleep1Threshold >= 0)
  191. {
  192. RuntimeThread.Sleep(1);
  193. }
  194. else
  195. {
  196. int yieldsSoFar = _count >= YieldThreshold ? (_count - YieldThreshold) / 2 : _count;
  197. if ((yieldsSoFar % Sleep0EveryHowManyYields) == (Sleep0EveryHowManyYields - 1))
  198. {
  199. RuntimeThread.Sleep(0);
  200. }
  201. else
  202. {
  203. RuntimeThread.Yield();
  204. }
  205. }
  206. }
  207. else
  208. {
  209. //
  210. // Otherwise, we will spin.
  211. //
  212. // We do this using the CLR's SpinWait API, which is just a busy loop that
  213. // issues YIELD/PAUSE instructions to ensure multi-threaded CPUs can react
  214. // intelligently to avoid starving. (These are NOOPs on other CPUs.) We
  215. // choose a number for the loop iteration count such that each successive
  216. // call spins for longer, to reduce cache contention. We cap the total
  217. // number of spins we are willing to tolerate to reduce delay to the caller,
  218. // since we expect most callers will eventually block anyway.
  219. //
  220. // Also, cap the maximum spin count to a value such that many thousands of CPU cycles would not be wasted doing
  221. // the equivalent of YieldProcessor(), as that that point SwitchToThread/Sleep(0) are more likely to be able to
  222. // allow other useful work to run. Long YieldProcessor() loops can help to reduce contention, but Sleep(1) is
  223. // usually better for that.
  224. //
  225. // RuntimeThread.OptimalMaxSpinWaitsPerSpinIteration:
  226. // - See Thread::InitializeYieldProcessorNormalized(), which describes and calculates this value.
  227. //
  228. int n = RuntimeThread.OptimalMaxSpinWaitsPerSpinIteration;
  229. if (_count <= 30 && (1 << _count) < n)
  230. {
  231. n = 1 << _count;
  232. }
  233. RuntimeThread.SpinWait(n);
  234. }
  235. // Finally, increment our spin counter.
  236. _count = (_count == int.MaxValue ? YieldThreshold : _count + 1);
  237. }
  238. /// <summary>
  239. /// Resets the spin counter.
  240. /// </summary>
  241. /// <remarks>
  242. /// This makes <see cref="SpinOnce()"/> and <see cref="NextSpinWillYield"/> behave as though no calls
  243. /// to <see cref="SpinOnce()"/> had been issued on this instance. If a <see cref="SpinWait"/> instance
  244. /// is reused many times, it may be useful to reset it to avoid yielding too soon.
  245. /// </remarks>
  246. public void Reset()
  247. {
  248. _count = 0;
  249. }
  250. #region Static Methods
  251. /// <summary>
  252. /// Spins until the specified condition is satisfied.
  253. /// </summary>
  254. /// <param name="condition">A delegate to be executed over and over until it returns true.</param>
  255. /// <exception cref="ArgumentNullException">The <paramref name="condition"/> argument is null.</exception>
  256. public static void SpinUntil(Func<bool> condition)
  257. {
  258. #if DEBUG
  259. bool result =
  260. #endif
  261. SpinUntil(condition, Timeout.Infinite);
  262. #if DEBUG
  263. Debug.Assert(result);
  264. #endif
  265. }
  266. /// <summary>
  267. /// Spins until the specified condition is satisfied or until the specified timeout is expired.
  268. /// </summary>
  269. /// <param name="condition">A delegate to be executed over and over until it returns true.</param>
  270. /// <param name="timeout">
  271. /// A <see cref="TimeSpan"/> that represents the number of milliseconds to wait,
  272. /// or a TimeSpan that represents -1 milliseconds to wait indefinitely.</param>
  273. /// <returns>True if the condition is satisfied within the timeout; otherwise, false</returns>
  274. /// <exception cref="ArgumentNullException">The <paramref name="condition"/> argument is null.</exception>
  275. /// <exception cref="T:System.ArgumentOutOfRangeException"><paramref name="timeout"/> is a negative number
  276. /// other than -1 milliseconds, which represents an infinite time-out -or- timeout is greater than
  277. /// <see cref="System.Int32.MaxValue"/>.</exception>
  278. public static bool SpinUntil(Func<bool> condition, TimeSpan timeout)
  279. {
  280. // Validate the timeout
  281. long totalMilliseconds = (long)timeout.TotalMilliseconds;
  282. if (totalMilliseconds < -1 || totalMilliseconds > int.MaxValue)
  283. {
  284. throw new System.ArgumentOutOfRangeException(
  285. nameof(timeout), timeout, SR.SpinWait_SpinUntil_TimeoutWrong);
  286. }
  287. // Call wait with the timeout milliseconds
  288. return SpinUntil(condition, (int)totalMilliseconds);
  289. }
  290. /// <summary>
  291. /// Spins until the specified condition is satisfied or until the specified timeout is expired.
  292. /// </summary>
  293. /// <param name="condition">A delegate to be executed over and over until it returns true.</param>
  294. /// <param name="millisecondsTimeout">The number of milliseconds to wait, or <see
  295. /// cref="System.Threading.Timeout.Infinite"/> (-1) to wait indefinitely.</param>
  296. /// <returns>True if the condition is satisfied within the timeout; otherwise, false</returns>
  297. /// <exception cref="ArgumentNullException">The <paramref name="condition"/> argument is null.</exception>
  298. /// <exception cref="T:System.ArgumentOutOfRangeException"><paramref name="millisecondsTimeout"/> is a
  299. /// negative number other than -1, which represents an infinite time-out.</exception>
  300. public static bool SpinUntil(Func<bool> condition, int millisecondsTimeout)
  301. {
  302. if (millisecondsTimeout < Timeout.Infinite)
  303. {
  304. throw new ArgumentOutOfRangeException(
  305. nameof(millisecondsTimeout), millisecondsTimeout, SR.SpinWait_SpinUntil_TimeoutWrong);
  306. }
  307. if (condition == null)
  308. {
  309. throw new ArgumentNullException(nameof(condition), SR.SpinWait_SpinUntil_ArgumentNull);
  310. }
  311. uint startTime = 0;
  312. if (millisecondsTimeout != 0 && millisecondsTimeout != Timeout.Infinite)
  313. {
  314. startTime = TimeoutHelper.GetTime();
  315. }
  316. SpinWait spinner = new SpinWait();
  317. while (!condition())
  318. {
  319. if (millisecondsTimeout == 0)
  320. {
  321. return false;
  322. }
  323. spinner.SpinOnce();
  324. if (millisecondsTimeout != Timeout.Infinite && spinner.NextSpinWillYield)
  325. {
  326. if (millisecondsTimeout <= (TimeoutHelper.GetTime() - startTime))
  327. {
  328. return false;
  329. }
  330. }
  331. }
  332. return true;
  333. }
  334. #endregion
  335. }
  336. /// <summary>
  337. /// A helper class to get the number of processors, it updates the numbers of processors every sampling interval.
  338. /// </summary>
  339. internal static class PlatformHelper
  340. {
  341. private const int PROCESSOR_COUNT_REFRESH_INTERVAL_MS = 30000; // How often to refresh the count, in milliseconds.
  342. private static volatile int s_processorCount; // The last count seen.
  343. private static volatile int s_lastProcessorCountRefreshTicks; // The last time we refreshed.
  344. /// <summary>
  345. /// Gets the number of available processors
  346. /// </summary>
  347. internal static int ProcessorCount
  348. {
  349. get
  350. {
  351. int now = Environment.TickCount;
  352. int procCount = s_processorCount;
  353. if (procCount == 0 || (now - s_lastProcessorCountRefreshTicks) >= PROCESSOR_COUNT_REFRESH_INTERVAL_MS)
  354. {
  355. s_processorCount = procCount = Environment.ProcessorCount;
  356. s_lastProcessorCountRefreshTicks = now;
  357. }
  358. Debug.Assert(procCount > 0,
  359. "Processor count should be greater than 0.");
  360. return procCount;
  361. }
  362. }
  363. /// <summary>
  364. /// Gets whether the current machine has only a single processor.
  365. /// </summary>
  366. /// <remarks>This typically does not change on a machine, so it's checked only once.</remarks>
  367. internal static readonly bool IsSingleProcessor = ProcessorCount == 1;
  368. }
  369. }