使用 Interlocked 测试并有条件地更新 long
有没有一种巧妙的方法可以使用 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
尝试
Interlocked.CompareExchange
方法。我还没有尝试过,但这样的事情对我来说似乎是合乎逻辑的:像往常一样,对代码进行压力测试以尝试捕获并发问题。
Try the
Interlocked.CompareExchange
method. I haven't tried, but something like this seems logical to me:As usual, stress test your code to try to catch concurrency issues.
只要共享字段的值只会增加,那么您就可以结合
读取
和CompareExchange
。但是,在这种情况下,我会选择普通的
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
andCompareExchange
.However, I would go for a plain
lock
in this situation: usingInterlocked
like this is less readable than alock
block and has the potential for much poorer performance too.