使用互锁
这段代码是线程安全的吗?或者这样说:
是否有办法调用 GetIt() 并且 GetIt() 会将相同的数字返回给 2 个不同的线程
Private Shared hitCount As Long = 1
Public Shared Function GetIt() As Long
Threading.Interlocked.Increment(hitCount)
DoSomethingQuick(hitCount)
Return hitCount
End Function
看起来这是可能的,那么我应该使用 Interlocked.Read()
还是将整个内容锁定在一个块中?
Is this code thread-safe? or put it this way:
Is there anyway to call GetIt() and that GetIt() will return the same number to 2 different threads
Private Shared hitCount As Long = 1
Public Shared Function GetIt() As Long
Threading.Interlocked.Increment(hitCount)
DoSomethingQuick(hitCount)
Return hitCount
End Function
It seems like it's possible, then am I supposed to use Interlocked.Read()
or lock the whole thing in one block?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
是的,有一种可能性:
Threading.Interlocked.Increment(hitCount)
Threading.Interlocked.Increment(hitCount)
返回 hitCount
返回 hitCount
在步骤 3 和 4 中,hitCount 将是相同的值。
但解决方法很简单 Interlocked.Increment 返回增量值,因此只需将代码更改为:
编辑
或者现在根据您的编辑,您有一个相当大的时间漏洞。不管怎样,这就是你想要的:
编辑
然后这样做(这正是迈克尔在下面建议的)
Yes there is a possibility:
Threading.Interlocked.Increment(hitCount)
Threading.Interlocked.Increment(hitCount)
Return hitCount
Return hitCount
In steps 3 and 4, hitCount will be the same value.
But the fix is easy Interlocked.Increment returns the incremented value, so just change your code to:
Edit
Or now based on your edit, you have a pretty bit timing hole. Anyway then this is what you want:
Edit
Then do this (which is exactly what Michael suggested below)