SpinWait.cs 18 KB

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