4

这段代码是线程安全的吗?或者这样说:

无论如何调用 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()或将整个东西锁定在一个块中吗?

4

1 回答 1

10

是的,有一种可能:

  1. 线程 1 运行Threading.Interlocked.Increment(hitCount)
  2. 线程 2 运行Threading.Interlocked.Increment(hitCount)
  3. 线程 1 运行Return hitCount
  4. 线程 2 运行Return hitCount

在第 3 步和第 4 步中,hitCount 将是相同的值。

但修复很容易 Interlocked.Increment 返回增量值,所以只需将代码更改为:

Private Shared hitCount As Long = 1L

Public Shared Function GetIt() As Long
     Return Threading.Interlocked.Increment(hitCount)
End Function

编辑 或者现在根据你的编辑,你有一个相当多的时间漏洞。无论如何,这就是你想要的:

Public Shared Function GetIt() As Long
     Dim localHitCount As Long = Threading.Interlocked.Increment(hitCount)
     Console.Writeline("Something, something....")
     Return localHitCount 
End Function

编辑 然后这样做(这正是迈克尔在下面建议的)

Private Shared hitCount As Long = 1L

Public Shared Function GetIt() As Long
     Dim localHitCount As Long = Threading.Interlocked.Increment(hitCount)
     DoSomethingQuick(localHitCount )
     Return localHitCount 
End Function
于 2010-02-09T17:21:11.293 回答