I’m new to threading and I came accross a custom thread pool implementation example in a blog. I’m pasting just the necessary parts of the code:
Public Class ThreadPool
Private CountLock As New Object
Private _Count As Integer
Public ReadOnly Property ThreadCount() As Integer
Get
SyncLock CountLock
Return _Count
End SyncLock
End Get
End Property
Public Sub Open()
Interlocked.Increment(_Count)
End Sub
Public Sub Close()
Interlocked.Decrement(_Count)
....
End Sub
EndClass
My question is, why do we need a lock to implement the readonly ThreadCount property?
The lock will force a memory barrier, so that a stale value from the CPU cache isn’t read if the last value written was written by a different CPU. The same could be done with
Thread.VolatileRead()without locking.