Why should I use SpinWait?

不羁岁月 提交于 2019-12-25 05:32:04

问题


I have written two lock-free update helper methods inspired by Joseph Albahari & Marc Gravell

Looking at the 2nd implementation why would I need the SpinWait in the 1st implementation? What are the advantables/disadvantages of one over the other?

Please note this question is not about what SpinWait does but rather specific to how these two methods differ in execution.

public static void LockFreeUpdate1<T>(ref T field, Func<T, T> updater) where T : class
{
    var spinner = new SpinWait();

    T snapshot;    
    while (true)
    {
        snapshot = field;

        if (snapshot.Equals(
               Interlocked.CompareExchange(ref field, updater(snapshot), snapshot))) { return; }

        spinner.SpinOnce();
    }
}


public static void LockFreeUpdate2<T>(ref T field, Func<T, T> updater) where T : class
{
    T snapshot;
    do
    {
        snapshot = field;                

    } while(
        snapshot.Equals(
           Interlocked.CompareExchange(ref field, updater(snapshot), snapshot)));
}

来源:https://stackoverflow.com/questions/31111056/why-should-i-use-spinwait

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!