In the following code:
a = Interlocked.Exchange(ref b, c);
I know b is set to c atomically. But is a also set to b in the same atomic operation? Or is this outside of the atomic operation.
What I need is to ensure both a and b are set in the same atomic operation.
c => b, b => a
This is in C#.Net.
I assume you’re considering code like this:
In that case, no, the operation isn’t atomic. In IL, there are two separate actions:
It would be entirely possible for another thread to “see”
ybecome 5 before the return value ofInterlocked.Exchangewas stored inx.Personally, if I were looking at something where you need multiple field values to be changed atomically, I’d be considering locks instead of atomic lock-free operations.