Created
August 8, 2018 20:24
-
-
Save adams85/06dc084c4b368624a935aac92fb7c77f to your computer and use it in GitHub Desktop.
SpinWait.SpinUntil lock test
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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