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