Skip to content

Instantly share code, notes, and snippets.

@adams85
Created August 8, 2018 20:24
Show Gist options
  • Save adams85/06dc084c4b368624a935aac92fb7c77f to your computer and use it in GitHub Desktop.
Save adams85/06dc084c4b368624a935aac92fb7c77f to your computer and use it in GitHub Desktop.
SpinWait.SpinUntil lock test
var flag = 0;
var stopwatch = new Stopwatch();
ParameterizedThreadStart task = p => {
SpinWait.SpinUntil(() => Interlocked.CompareExchange(ref flag, 1, 0) == 0);
Console.WriteLine($"[{stopwatch.Elapsed}] Thread {p} has entered lock.");
Thread.Sleep(2000);
Console.WriteLine($"[{stopwatch.Elapsed}] Thread {p} is exiting lock.");
Interlocked.Exchange(ref flag, 0);
};
var thread1 = new Thread(task);
var thread2 = new Thread(task);
stopwatch.Start();
thread1.Start(1);
thread2.Start(2);
thread1.Join();
thread2.Join();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment