Search code examples
c#atomic

Is compound assignment ^= atomic in C#?


I wonder if compound assignment ^= is atomic in C#. What I really need to do is spin (if the value is 0 then set it to 1 and if it is 1 then set it to 0) an Int32 variable with a single atomic operation.


Solution

  • As answered above, x^=1 is not atomic. Could you use Interlocked.Increment (which is atomic) and then, when reading, consider the value % 2?