Implement CompareAndSwap for bool

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

+4
source share
2 answers

You can define Boolean wrapper values โ€‹โ€‹and use CompareExchange overload for T where T : class , for example:

 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) ... ... } 
+4
source

An alternative to the dablinkenlight approach would be to use Int32 overload, where 0 is false and any nonzero value is true .

0
source

Source: https://habr.com/ru/post/1488974/


All Articles