a little further with System.Threading.Interlocked class
-
ok so perhaps not c# specific but its the language im using so... i have some (hopefully) thread-safe code that accesses some shared fields using the
lock
statement but im trying to avoid full-on locking. i need to update a field only if the result does not exceed some other value. i found the following code for simple value update (in the CompareExchange() example):do {
initialValue = totalValue;
computedValue = initialValue + addend;
} while (initialValue != Interlocked.CompareExchange(ref totalValue, computedValue, initialValue));now, if i use the following would it be properly thread-safe and do wot i need..?
do {
initialValue = originalValue;
result = initialValue + addValue;
overFlag = result > maxValue;
if (overFlag) result = initialValue;
} while (initialValue != Interlocked.CompareExchange(ref originalValue, result, initialValue));overFlag
isbool
and would be used after the udpate code to determine whether to continue or not. i cant quite get my head around it. :confused: thanks in advance
I worship his divine shadow.