使用 Interlocked 测试并有条件地更新 long

发布于 2024-11-19 14:45:15 字数 139 浏览 3 评论 0原文

有没有一种巧妙的方法可以使用 Interlocked 类来做到这一点?或者我应该只使用 lock { }

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

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

对你的占有欲 2024-11-26 14:45:15

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

long localMax = Interlocked.Read(ref max);
while (value > localMax) {
  Interlocked.CompareExchange(ref max, value, localMax);
  localMax = Interlocked.Read(ref max);
}

像往常一样,对代码进行压力测试以尝试捕获并发问题。

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.

往日情怀 2024-11-26 14:45:15

只要共享字段的值只会增加,那么您就可以结合 读取CompareExchange

long sharedVal = Interlocked.Read(ref _sharedField);
while (localVal > sharedVal)
{
    long temp = Interlocked.CompareExchange(ref _sharedField, localVal, sharedVal);
    sharedVal = (temp == sharedVal) ? localVal : temp;
}

但是,在这种情况下,我会选择普通的 lock:像这样使用 Interlocked 的可读性不如 lock 块,并且有可能性能也差很多。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文