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();
}
}
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?