Using lock

Is this code thread safe? or put it this way:

Is there a way to call GetIt () and that GetIt () will return the same number in 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 to be possible, then should I use Interlocked.Read() or block it all in one block?

+4
source share
1 answer

Yes, there is a possibility:

  • Topic 1 launches Threading.Interlocked.Increment(hitCount)
  • Topic 2 launches Threading.Interlocked.Increment(hitCount)
  • Theme 1 launches Return hitCount
  • Theme 2 launches Return hitCount

In steps 3 and 4, hitCount will have the same value.

But the fix is ​​easy Interlocked.Increment returns an extra value, so just change your code to:

 Private Shared hitCount As Long = 1L Public Shared Function GetIt() As Long Return Threading.Interlocked.Increment(hitCount) End Function 

Edit Or now, based on your editing, you have a pretty small time hole. Anyway, this is what you want:

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

Edit Then do it (this is exactly what Michael suggested below)

 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 
+10
source

Source: https://habr.com/ru/post/1300773/


All Articles