You can atomically update a variable without locking with Interlocked.CompareExchange until you succeed. This avoids the overhead of locking while ensuring consistency, this pseudocode should do this, sorry, I'm not too familiar with C #.
static void atomic_add(ref int ptr, int addend){ int previous = *ptr; while(1){ int observed = Interlocked.CompareExchange(ptr, previous+addend, previous); if(observed == previous){ break; }else{ previous = observed; } } }
CompareExchange will replace the value in the first argument with the second argument if the value specified by the first argument is equal to the third argument and returns the value in memory in ptr when CompareExchange is called. If the value returned by the exchange of the exchange matches the previous value observed in ptr, then the value was successfully updated and the cycle is interrupted, otherwise the value in the pointer has changed since the last update of the last and previous, and we will try again.
From what I read, Interlocked.CompareExchange exists only for int32, floats and objects (although not sure if it will be completely blocked?). I suppose that this will work for wider values on 64-bit platforms, but I have nothing to support it.
miishuu
source share