SpinWait.cs 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388
  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. // The number of times we've spun already.
  87. private int _count;
  88. /// <summary>
  89. /// Gets the number of times <see cref="SpinOnce()"/> has been called on this instance.
  90. /// </summary>
  91. public int Count
  92. {
  93. get => _count;
  94. internal set
  95. {
  96. Debug.Assert(value >= 0);
  97. _count = value;
  98. }
  99. }
  100. /// <summary>
  101. /// Gets whether the next call to <see cref="SpinOnce()"/> will yield the processor, triggering a
  102. /// forced context switch.
  103. /// </summary>
  104. /// <value>Whether the next call to <see cref="SpinOnce()"/> will yield the processor, triggering a
  105. /// forced context switch.</value>
  106. /// <remarks>
  107. /// On a single-CPU machine, <see cref="SpinOnce()"/> always yields the processor. On machines with
  108. /// multiple CPUs, <see cref="SpinOnce()"/> may yield after an unspecified number of calls.
  109. /// </remarks>
  110. public bool NextSpinWillYield => _count >= YieldThreshold || PlatformHelper.IsSingleProcessor;
  111. /// <summary>
  112. /// Performs a single spin.
  113. /// </summary>
  114. /// <remarks>
  115. /// This is typically called in a loop, and may change in behavior based on the number of times a
  116. /// <see cref="SpinOnce()"/> has been called thus far on this instance.
  117. /// </remarks>
  118. public void SpinOnce()
  119. {
  120. SpinOnceCore(DefaultSleep1Threshold);
  121. }
  122. /// <summary>
  123. /// Performs a single spin.
  124. /// </summary>
  125. /// <param name="sleep1Threshold">
  126. /// A minimum spin count after which <code>Thread.Sleep(1)</code> may be used. A value of <code>-1</code> may be used to
  127. /// disable the use of <code>Thread.Sleep(1)</code>.
  128. /// </param>
  129. /// <exception cref="ArgumentOutOfRangeException">
  130. /// <paramref name="sleep1Threshold"/> is less than <code>-1</code>.
  131. /// </exception>
  132. /// <remarks>
  133. /// This is typically called in a loop, and may change in behavior based on the number of times a
  134. /// <see cref="SpinOnce()"/> has been called thus far on this instance.
  135. /// </remarks>
  136. public void SpinOnce(int sleep1Threshold)
  137. {
  138. if (sleep1Threshold < -1)
  139. {
  140. throw new ArgumentOutOfRangeException(nameof(sleep1Threshold), sleep1Threshold, SR.ArgumentOutOfRange_NeedNonNegOrNegative1);
  141. }
  142. if (sleep1Threshold >= 0 && sleep1Threshold < YieldThreshold)
  143. {
  144. sleep1Threshold = YieldThreshold;
  145. }
  146. SpinOnceCore(sleep1Threshold);
  147. }
  148. private void SpinOnceCore(int sleep1Threshold)
  149. {
  150. Debug.Assert(sleep1Threshold >= -1);
  151. Debug.Assert(sleep1Threshold < 0 || sleep1Threshold >= YieldThreshold);
  152. // (_count - YieldThreshold) % 2 == 0: The purpose of this check is to interleave Thread.Yield/Sleep(0) with
  153. // Thread.SpinWait. Otherwise, the following issues occur:
  154. // - When there are no threads to switch to, Yield and Sleep(0) become no-op and it turns the spin loop into a
  155. // busy-spin that may quickly reach the max spin count and cause the thread to enter a wait state, or may
  156. // just busy-spin for longer than desired before a Sleep(1). Completing the spin loop too early can cause
  157. // excessive context switcing if a wait follows, and entering the Sleep(1) stage too early can cause
  158. // excessive delays.
  159. // - If there are multiple threads doing Yield and Sleep(0) (typically from the same spin loop due to
  160. // contention), they may switch between one another, delaying work that can make progress.
  161. if ((
  162. _count >= YieldThreshold &&
  163. ((_count >= sleep1Threshold && sleep1Threshold >= 0) || (_count - YieldThreshold) % 2 == 0)
  164. ) ||
  165. PlatformHelper.IsSingleProcessor)
  166. {
  167. //
  168. // We must yield.
  169. //
  170. // We prefer to call Thread.Yield first, triggering a SwitchToThread. This
  171. // unfortunately doesn't consider all runnable threads on all OS SKUs. In
  172. // some cases, it may only consult the runnable threads whose ideal processor
  173. // is the one currently executing code. Thus we occasionally issue a call to
  174. // Sleep(0), which considers all runnable threads at equal priority. Even this
  175. // is insufficient since we may be spin waiting for lower priority threads to
  176. // execute; we therefore must call Sleep(1) once in a while too, which considers
  177. // all runnable threads, regardless of ideal processor and priority, but may
  178. // remove the thread from the scheduler's queue for 10+ms, if the system is
  179. // configured to use the (default) coarse-grained system timer.
  180. //
  181. if (_count >= sleep1Threshold && sleep1Threshold >= 0)
  182. {
  183. RuntimeThread.Sleep(1);
  184. }
  185. else
  186. {
  187. int yieldsSoFar = _count >= YieldThreshold ? (_count - YieldThreshold) / 2 : _count;
  188. if ((yieldsSoFar % Sleep0EveryHowManyYields) == (Sleep0EveryHowManyYields - 1))
  189. {
  190. RuntimeThread.Sleep(0);
  191. }
  192. else
  193. {
  194. RuntimeThread.Yield();
  195. }
  196. }
  197. }
  198. else
  199. {
  200. //
  201. // Otherwise, we will spin.
  202. //
  203. // We do this using the CLR's SpinWait API, which is just a busy loop that
  204. // issues YIELD/PAUSE instructions to ensure multi-threaded CPUs can react
  205. // intelligently to avoid starving. (These are NOOPs on other CPUs.) We
  206. // choose a number for the loop iteration count such that each successive
  207. // call spins for longer, to reduce cache contention. We cap the total
  208. // number of spins we are willing to tolerate to reduce delay to the caller,
  209. // since we expect most callers will eventually block anyway.
  210. //
  211. // Also, cap the maximum spin count to a value such that many thousands of CPU cycles would not be wasted doing
  212. // the equivalent of YieldProcessor(), as that that point SwitchToThread/Sleep(0) are more likely to be able to
  213. // allow other useful work to run. Long YieldProcessor() loops can help to reduce contention, but Sleep(1) is
  214. // usually better for that.
  215. //
  216. // RuntimeThread.OptimalMaxSpinWaitsPerSpinIteration:
  217. // - See Thread::InitializeYieldProcessorNormalized(), which describes and calculates this value.
  218. //
  219. int n = RuntimeThread.OptimalMaxSpinWaitsPerSpinIteration;
  220. if (_count <= 30 && (1 << _count) < n)
  221. {
  222. n = 1 << _count;
  223. }
  224. RuntimeThread.SpinWait(n);
  225. }
  226. // Finally, increment our spin counter.
  227. _count = (_count == int.MaxValue ? YieldThreshold : _count + 1);
  228. }
  229. /// <summary>
  230. /// Resets the spin counter.
  231. /// </summary>
  232. /// <remarks>
  233. /// This makes <see cref="SpinOnce()"/> and <see cref="NextSpinWillYield"/> behave as though no calls
  234. /// to <see cref="SpinOnce()"/> had been issued on this instance. If a <see cref="SpinWait"/> instance
  235. /// is reused many times, it may be useful to reset it to avoid yielding too soon.
  236. /// </remarks>
  237. public void Reset()
  238. {
  239. _count = 0;
  240. }
  241. #region Static Methods
  242. /// <summary>
  243. /// Spins until the specified condition is satisfied.
  244. /// </summary>
  245. /// <param name="condition">A delegate to be executed over and over until it returns true.</param>
  246. /// <exception cref="ArgumentNullException">The <paramref name="condition"/> argument is null.</exception>
  247. public static void SpinUntil(Func<bool> condition)
  248. {
  249. #if DEBUG
  250. bool result =
  251. #endif
  252. SpinUntil(condition, Timeout.Infinite);
  253. #if DEBUG
  254. Debug.Assert(result);
  255. #endif
  256. }
  257. /// <summary>
  258. /// Spins until the specified condition is satisfied or until the specified timeout is expired.
  259. /// </summary>
  260. /// <param name="condition">A delegate to be executed over and over until it returns true.</param>
  261. /// <param name="timeout">
  262. /// A <see cref="TimeSpan"/> that represents the number of milliseconds to wait,
  263. /// or a TimeSpan that represents -1 milliseconds to wait indefinitely.</param>
  264. /// <returns>True if the condition is satisfied within the timeout; otherwise, false</returns>
  265. /// <exception cref="ArgumentNullException">The <paramref name="condition"/> argument is null.</exception>
  266. /// <exception cref="T:System.ArgumentOutOfRangeException"><paramref name="timeout"/> is a negative number
  267. /// other than -1 milliseconds, which represents an infinite time-out -or- timeout is greater than
  268. /// <see cref="System.Int32.MaxValue"/>.</exception>
  269. public static bool SpinUntil(Func<bool> condition, TimeSpan timeout)
  270. {
  271. // Validate the timeout
  272. long totalMilliseconds = (long)timeout.TotalMilliseconds;
  273. if (totalMilliseconds < -1 || totalMilliseconds > int.MaxValue)
  274. {
  275. throw new System.ArgumentOutOfRangeException(
  276. nameof(timeout), timeout, SR.SpinWait_SpinUntil_TimeoutWrong);
  277. }
  278. // Call wait with the timeout milliseconds
  279. return SpinUntil(condition, (int)totalMilliseconds);
  280. }
  281. /// <summary>
  282. /// Spins until the specified condition is satisfied or until the specified timeout is expired.
  283. /// </summary>
  284. /// <param name="condition">A delegate to be executed over and over until it returns true.</param>
  285. /// <param name="millisecondsTimeout">The number of milliseconds to wait, or <see
  286. /// cref="System.Threading.Timeout.Infinite"/> (-1) to wait indefinitely.</param>
  287. /// <returns>True if the condition is satisfied within the timeout; otherwise, false</returns>
  288. /// <exception cref="ArgumentNullException">The <paramref name="condition"/> argument is null.</exception>
  289. /// <exception cref="T:System.ArgumentOutOfRangeException"><paramref name="millisecondsTimeout"/> is a
  290. /// negative number other than -1, which represents an infinite time-out.</exception>
  291. public static bool SpinUntil(Func<bool> condition, int millisecondsTimeout)
  292. {
  293. if (millisecondsTimeout < Timeout.Infinite)
  294. {
  295. throw new ArgumentOutOfRangeException(
  296. nameof(millisecondsTimeout), millisecondsTimeout, SR.SpinWait_SpinUntil_TimeoutWrong);
  297. }
  298. if (condition == null)
  299. {
  300. throw new ArgumentNullException(nameof(condition), SR.SpinWait_SpinUntil_ArgumentNull);
  301. }
  302. uint startTime = 0;
  303. if (millisecondsTimeout != 0 && millisecondsTimeout != Timeout.Infinite)
  304. {
  305. startTime = TimeoutHelper.GetTime();
  306. }
  307. SpinWait spinner = new SpinWait();
  308. while (!condition())
  309. {
  310. if (millisecondsTimeout == 0)
  311. {
  312. return false;
  313. }
  314. spinner.SpinOnce();
  315. if (millisecondsTimeout != Timeout.Infinite && spinner.NextSpinWillYield)
  316. {
  317. if (millisecondsTimeout <= (TimeoutHelper.GetTime() - startTime))
  318. {
  319. return false;
  320. }
  321. }
  322. }
  323. return true;
  324. }
  325. #endregion
  326. }
  327. /// <summary>
  328. /// A helper class to get the number of processors, it updates the numbers of processors every sampling interval.
  329. /// </summary>
  330. internal static class PlatformHelper
  331. {
  332. private const int PROCESSOR_COUNT_REFRESH_INTERVAL_MS = 30000; // How often to refresh the count, in milliseconds.
  333. private static volatile int s_processorCount; // The last count seen.
  334. private static volatile int s_lastProcessorCountRefreshTicks; // The last time we refreshed.
  335. /// <summary>
  336. /// Gets the number of available processors
  337. /// </summary>
  338. internal static int ProcessorCount
  339. {
  340. get
  341. {
  342. int now = Environment.TickCount;
  343. int procCount = s_processorCount;
  344. if (procCount == 0 || (now - s_lastProcessorCountRefreshTicks) >= PROCESSOR_COUNT_REFRESH_INTERVAL_MS)
  345. {
  346. s_processorCount = procCount = Environment.ProcessorCount;
  347. s_lastProcessorCountRefreshTicks = now;
  348. }
  349. Debug.Assert(procCount > 0,
  350. "Processor count should be greater than 0.");
  351. return procCount;
  352. }
  353. }
  354. /// <summary>
  355. /// Gets whether the current machine has only a single processor.
  356. /// </summary>
  357. /// <remarks>This typically does not change on a machine, so it's checked only once.</remarks>
  358. internal static readonly bool IsSingleProcessor = ProcessorCount == 1;
  359. }
  360. }