无锁更新中的SpinWait

编程入门 行业动态 更新时间:2024-10-22 17:32:07
本文介绍了无锁更新中的SpinWait的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

在阅读 Albahari在C#中的线程时,我注意到锁定免费更新"模式在周期结束时使用SpinWait:

While reading Albahari's Threading in C#, I've noticed that the "lock free update" pattern uses a SpinWait at the end of the cycle:

static void LockFreeUpdate<T> (ref T field, Func <T, T> updateFunction) where T : class { var spinWait = new SpinWait(); while (true) { // read T snapshot1 = field; // apply transformation T calc = updateFunction (snapshot1); // compare if not preempted T snapshot2 = Interlocked.CompareExchange (ref field, calc, snapshot1); // if succeeded, we're done if (snapshot1 == snapshot2) return; // otherwise spin spinWait.SpinOnce(); } }

注意最后的spinWait.SpinOnce()调用.是仅在单线程环境中产生线程才需要此调用,还是有其他目的?

Note the spinWait.SpinOnce() call at the end. Is this call needed only to yield the thread in a single-threaded environment, or does it have an additional purpose?

推荐答案

简短答案...是. SpinWait的目的是允许将线程产生给系统,以免由于SpinLock而导致处理不足.

Short answer... Yes. The intent of SpinWait is to allow yielding the thread to the System so as not to starve processing due to SpinLock.

从MSDN

msdn .microsoft/en-us/library/system.threading.spinwait(v = vs.110).aspx

SpinWait封装了常见的旋转逻辑.在单处理器上 机器上,始终使用收益来代替繁忙的等待,等等 装有采用超线程技术的英特尔处理器的计算机, 它有助于防止硬件线程不足. SpinWait封装 纺纱和真实产量的良好混合物.

SpinWait encapsulates common spinning logic. On single-processor machines, yields are always used instead of busy waits, and on computers with Intel processors employing Hyper-Threading technology, it helps to prevent hardware thread starvation. SpinWait encapsulates a good mixture of spinning and true yielding.

SpinWait是一种值类型,这意味着低级代码可以利用 SpinWait,无需担心不必要的分配开销. SpinWait是 通常不适用于普通应用.在大多数情况下,您 应该使用.NET Framework提供的同步类, 例如Monitor.对于大多数需要旋转等待的用途, 但是,应该优先使用SpinWait类型而不是SpinWait 方法.

SpinWait is a value type, which means that low-level code can utilize SpinWait without fear of unnecessary allocation overheads. SpinWait is not generally useful for ordinary applications. In most cases, you should use the synchronization classes provided by the .NET Framework, such as Monitor. For most purposes where spin waiting is required, however, the SpinWait type should be preferred over the SpinWait method.

更多推荐

无锁更新中的SpinWait

本文发布于:2023-11-30 20:04:14,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1651333.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:更新中   SpinWait

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!