Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Implement CompareAndSwap for bool

In .NET framework, atomic operation CompareAndExchange is only defined for int, long, double and reference type. But I need CompareAndExchange for bool type. How can I implement CompareAndSwap for bool?

like image 721
user Avatar asked Jun 30 '13 17:06

user


2 Answers

You can define wrapper boolean values, and use the CompareExchange overload for T where T : class, like this:

private static object TrueObj = true;
private static object FalseObj = false;
...
object val = TrueObj;
object result = Interlocked.CompareExchange(ref val, TrueObj, FalseObj);
if (val == FalseObj) { // Alternatively you could use if (!(bool)val) ...
    ...
}
like image 149
Sergey Kalinichenko Avatar answered Oct 03 '22 04:10

Sergey Kalinichenko


An alternative to dablinkenlight's approach would be to use the Int32 overload where 0 is false and any non-zero value is true.

like image 43
keyboardP Avatar answered Oct 03 '22 04:10

keyboardP