在阅读 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
发布评论