Can the compiler or processor reorder the following instructions so that another Thread sees a == 0
and b == 1
?
Assuming int a = 0, b = 0;
somewhere.
System.Threading.Interlocked.CompareExchange<int>(ref a, 1, 0);
System.Threading.Interlocked.CompareExchange<int>(ref b, 1, 0);
No. Using
Interlock
will signal a full memory fence. “That is, any variable writes before the call to anInterlocked
method execute before theInterlocked
method, and any variable reads after the call executes after the call.” [1] They use volatile read/write methods to prevent theb = 1
beforea = 1
.[1]: Jeffrey Richter: “CLR via C# - Third Edition” part V Threading, page 803