I don't know why, but I can't quite seem to wrap my head around what's going on in Interlocked.CompareExchange(ref int a, int b, int c)
.
Could someone show me what it would be doing, if it were just naively implemented in a single-threaded environment?
i.e. what code is it replacing with a "do that ... but as an atomic, thread-safe operation"?
Here's my understanding of the code (in single-threaded land):
static int CompareExchange(ref int location1, int value, int comparand)
{
var valueToReturn = location1;
if (location1 == comparand)
{
location1 = value;
}
return valueToReturn;
}
Taken from the docs here: https://learn.microsoft.com/en-us/dotnet/api/system.threading.interlocked.compareexchange
Parameters
Remarks
If comparand and the value in location1 are equal, then value is stored in location1. Otherwise, no operation is performed. The compare and exchange operations are performed as an atomic operation. The return value of CompareExchange is the original value in location1, whether or not the exchange takes place.