Test and conditionally update a long using Interlocked
Is there a neat way to do this using the Interlocked
class? Or should I just use lock { }
?
My specific use case is that I have multiple threads that compute a long
value, and compare it to a shared "Maximum" value, replacing the shared value开发者_Python百科 only if the local value is larger.
Try the Interlocked.CompareExchange
method. I haven't tried, but something like this seems logical to me:
long localMax = Interlocked.Read(ref max);
while (value > localMax) {
Interlocked.CompareExchange(ref max, value, localMax);
localMax = Interlocked.Read(ref max);
}
As usual, stress test your code to try to catch concurrency issues.
So long as the value of your shared field only ever increases then you could do something like this with a combination of Read
and CompareExchange
.
long sharedVal = Interlocked.Read(ref _sharedField);
while (localVal > sharedVal)
{
long temp = Interlocked.CompareExchange(ref _sharedField, localVal, sharedVal);
sharedVal = (temp == sharedVal) ? localVal : temp;
}
However, I would go for a plain lock
in this situation: using Interlocked
like this is less readable than a lock
block and has the potential for much poorer performance too.
精彩评论