Created
March 2, 2019 19:58
-
-
Save mstum/c351da021577d1f547bf9246f10dce2e to your computer and use it in GitHub Desktop.
AtomicFlag
This file contains 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
class Program | |
{ | |
static void Main(string[] args) | |
{ | |
var f = new AtomicFlag(true); | |
Console.WriteLine($"Value: {f.Value}"); | |
var oldVal = f.CompareExchange(true, false); | |
Console.WriteLine($"Old Val: {oldVal}, Value: {f.Value}"); | |
oldVal = f.CompareExchange(true, false); | |
Console.WriteLine($"Old Val: {oldVal}, Value: {f.Value}"); | |
oldVal = f.CompareExchange(false, true); | |
Console.WriteLine($"Old Val: {oldVal}, Value: {f.Value}"); | |
oldVal = f.CompareExchange(true, false); | |
Console.WriteLine($"Old Val: {oldVal}, Value: {f.Value}"); | |
Console.ReadLine(); | |
} | |
} | |
public struct AtomicFlag | |
{ | |
private const int FalseValue = 0; | |
private const int TrueValue = -1; | |
private int _value; | |
public AtomicFlag(bool value) | |
{ | |
_value = value ? TrueValue : FalseValue; | |
} | |
public bool Value => _value == TrueValue; | |
public bool CompareExchange(bool valueToSetTo, bool valueToCheckAgainst) | |
{ | |
return Interlocked.CompareExchange(ref _value, | |
valueToSetTo ? TrueValue : FalseValue, | |
valueToCheckAgainst ? TrueValue : FalseValue) | |
== TrueValue; | |
} | |
/*public static implicit operator AtomicFlag(bool input) | |
=> new AtomicFlag(input); | |
public static implicit operator bool(AtomicFlag input) | |
=> input.Value;*/ | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment