I posted this to badbrams block and chrisbrumme blog. Post here to get more
eyes.
Does this spin version work? Why or why not? Cheers!
public sealed class Singleton
{
private static int spinLock = 0; // lock not owned.
private static Singleton value = null;
private Singleton() {}
public static Singleton Value()
{
// Get spin lock.
while ( Interlocked.Exchange(ref spinLock, 1) != 0 )
Thread.Sleep(0);
// Do we have any mbarrier issues?
if ( value == null )
value = new Singleton();
Interlocked.Exchange(ref spinLock, 0);
return value;
}
}
This would help answer a few related questions for me on how Interlocked
works with mem barriers and cache, etc. TIA -- William