使用 Interlocked 测试并有条件地更新 long [英] Test and conditionally update a long using Interlocked

查看:33
本文介绍了使用 Interlocked 测试并有条件地更新 long的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有使用 Interlocked 类的巧妙方法来做到这一点?或者我应该只使用 lock { } 吗?

Is there a neat way to do this using the Interlocked class? Or should I just use lock { }?

我的具体用例是我有多个线程来计算 long 值,并将其与共享的最大值"值进行比较,仅当本地值较大时才替换共享值.

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 only if the local value is larger.

推荐答案

试试 Interlocked.CompareExchange 方法.我没试过,但这样的事情对我来说似乎合乎逻辑:

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.

这篇关于使用 Interlocked 测试并有条件地更新 long的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆