I have a situation where multiple threads may access a class, the class consists of 3 private values and 6 properties that get/set various arithmetic combinations of the 3 values. Then I have 6 more properties that are just type conversions as they call on the first 6 properties as a part of their get/set operation.
All the get/set functions of the first 6 properties are synclocked to the same object. I wanted to synclock the get/set functions of the other 6 too to the same object since they use some of the same utility objects but it occurred to me that this will lead to synclocking the same object twice in a row.. sorta like this:
Private lock As New Object
Private _dCool As Double
Public Property dCool As Double
Get
SyncLock lock
Return _dCool
End SyncLock
End Get
Set(value As Double)
SyncLock lock
_dCool = value
End SyncLock
End Set
End Property
Public Property iCool As Integer
Get
SyncLock lock
Return dCool
End SyncLock
End Get
Set(value As Integer)
SyncLock lock
dCool = value
End SyncLock
End Set
End Property
There is no need to synclock iCool in this example but its just to illustrate the problem. As far as I've tested, there seem to be no problems with this but just wanted to ask if some problems i cant see right now could come up by doing this?
Yes, not a problem. The VB.NET compiler generates calls to Monitor.Enter/Exit() when you use the SyncLock keyword, along with Try/Finally blocks to ensure that the entered monitor is always exited. The MSDN article for Monitor.Enter says:
It is legal for the same thread to invoke Enter more than once without it blocking; however, an equal number of Exit calls must be invoked before other threads waiting on the object will unblock.
Relevant phrase bolded. The Finally block ensure that the Exit() call requirement is always met.
Related
I have one class implementing ISerializable interface, with one private field that is saved and retrieved:
Protected Sub New(ByVal info As SerializationInfo, ByVal context As StreamingContext)
_name= info.GetString("_name")
End Sub
Now, I want to add a new private field, but since it did not exist previously, when I try to open a serialized object I get an exception when trying to get this field, in the custom deserialization constructor. The solution I've come up with is to use a Try...Catch block, as follows:
Protected Sub New(ByVal info As SerializationInfo, _
ByVal context As StreamingContext)
_name= info.GetString("_name")
Try
_active= info.GetBoolean("_active")
Catch ex As Exception
_active= False
End Try
End Sub
It works, but it seems a bit messy to me, moreover because I will have to add a new Try...Catch block for each new field I want to add.
Is there any better way of doing this?
Thanks!
EDIT:
In this answer t0mm13b says that "There is a more neater way to do this in 2.0+ upwards". Any ideas about what is he talking about?
There is no built-in method that allows you to first determine if a particular value exists (e.g. Exists). There is also no Get... method which simply returns Nothing if the value does not exist (e.g. TryGet). However, the one way that you can do it which avoids the potential for exceptions is to use a For Each loop to iterate through all of the values in the SerializationInfo collection. For instance:
For Each i As SerializationEntry In info
Select Case i.Name
Case "_name"
_name = DirectCast(i.Value, String)
' ...
End Select
Next
Note: It may be surprising to you that you can use a For Each loop on a SerializationInfo object, since it does not implement the IEnumerable interface (nor the generic equivalent). However, For Each in VB.NET actually works with any object that has a public GetEnumerator method. So, even though it leads to some confusion, objects don't technically need to implement IEnumerable in order for you to iterate through them with a For Each loop. Since the SerializationInfo class does expose a public GetEnumerator method, you can iterate through it with a For Each loop.
I've got a backgroundworker implemented in my program and it's accessing a global variable decalred outside the thread. IT causes no errors but setting the checkillegalstring property and there are cross thread exceptions all over the place. I found out that it's because it's using the global variable I've declared previously.
I can't seem to find anywhere that I can use a global variable inside my backgroundworker thread, is this possible to do?
The simplest way is with SyncLock
Sub firstNewThread()
SyncLock objLock
'Access global object
End SyncLock
End Sub
Sub secondNewThread()
SyncLock objLock
'Guaranteed to not be executing while block in first thread is running
End SyncLock
End Sub
Just be aware of other pitfalls like deadlocks that may occur from this.
Perhaps you can try SyncLock.
See this answer: https://stackoverflow.com/a/915877/153923
For example:
// C#
lock (someLock)
{
list.Add(someItem);
}
// VB
SyncLock someLock
list.Add(someItem)
End SyncLock
In the following example GetList returns an instance of a static (shared) variable. That one needs locking in order to be thread-safe.
But what about DoSomething which doesn't use any static variables outside the method? Does it need locking too?
EDIT: I'd like to clarify that in this particular case I expect DoSomething to always print 0-100 in sequence (i.e. no 0123745...) regardless of number of calling threads. Or, in general, that different threads don't affect each other's variables (printing to console is only an example). The language in the following example is VB.NET.
As paxdiablo said:
In this case, it appears the only thing touched is the local variable
i which would have a separate copy for every function invocation.
In other words, it wouldn't need protecting.
That is exactly what I was trying to solve. Thank you!
Public Class TestClass
Private Shared lock As New Object
Private Shared list As List(Of Integer)
Public Shared Function GetList() As List(Of Integer)
SyncLock lock
If list Is Nothing Then
list = New List(Of Integer)
End If
Return list
End SyncLock
End Function
Public Shared Sub DoSomething()
Dim i As Integer
For i = 0 To 100
Console.WriteLine(i.ToString)
Next
End Sub
End Class
Well, that would mostly depend on the language which you haven't specified but, generally, if code doesn't touch a resource that another thread can also touch, it doesn't have to be protected.
In this case, it appears the only thing touched is the local variable i which would have a separate copy for every function invocation. In other words, it wouldn't need protecting.
Of course, it could be argued that the console is also a resource and may need protection if, for example, you didn't want lines interfering with each other (synclock the write) or wanted the entire hundred lines output as a single unit (synclock the entire for loop).
But that won't really protect the console, just the block of code here that uses it. Other threads will still be able to write to the console by not using this method.
Bottom line, I don't think you need a synclock in the second method.
This section below is not relevant if you're using SyncLock in VB.Net (as now seems to be the case). The language guarantees that the lock is released no matter how you leave the block. I'll leave it in for hysterical purposes.
I'd be a little concerned about your synclock placement in the first method, especially if the return statement was a transfer of control back to the caller (and the synclock didn't automatically unlock on scope change). This looks like you can return without unlocking, which would be a disaster. I would think the following would be more suitable:
Public Shared Function GetList() As List(Of Integer)
SyncLock lock
If list Is Nothing Then
list = New List(Of Integer)
End If
End SyncLock
Return list
End Function
In general, no.
You need to be clear on the reason why GetList has the locking applied. It's not, as you imply in your first sentence, because it's returning a static variable. You could remove the locking code, and GetList would still be thread safe. But, with the locking, there's an additional guarantee - that the list will only be created once, and all callers of this code will receive a reference to the same list.
Why not avoid the lock altogether and just do this:
Public Class TestClass
Private Shared lock As New Object
Private Shared list As New List(Of Integer)
Public Shared Function GetList() As List(Of Integer)
Return list
End Function
Public Shared Sub DoSomething()
Dim i As Integer
For i = 0 To 100
Console.WriteLine(i.ToString)
Next
End Sub
End Class
I am currently using Florian Leitner's HID USB library in my VB.NET solution for communicating with a pin pad. As per his sample code, I set up an event handler to handle incoming responses from the device which are stored in an ArrayList called usbBuffer:
Private Sub BufferEventHandler(ByVal sender As Object, ByVal e As System.EventArgs)
If USBInterface.usbBuffer.Count > 0 Then
While USBInterface.usbBuffer(0) Is Nothing
SyncLock USBInterface.usbBuffer.SyncRoot
USBInterface.usbBuffer.RemoveAt(0)
End SyncLock
End While
_receiveArray = CType(USBInterface.usbBuffer(0), Byte())
_usbInterface.stopRead()
SyncLock USBInterface.usbBuffer.SyncRoot
USBInterface.usbBuffer.RemoveAt(0)
End SyncLock
End If
End Sub
The problem is that the RemoveAt is not working, since the first element in the list remains there after the handler is done. Could someone please advise as to what I've done wrong, or perhaps use a different approach?
msdn says that the object of the synclock cannot be nothing.
and you cannot cjhange the value of the lockobject.
msdn http://msdn.microsoft.com/en-us/library/3a86s51t(VS.80).aspx says
Rules
Lock Object Value. The value of lockobject cannot be Nothing. You must create the lock object before you use it in a SyncLock statement.
You cannot change the value of lockobject while executing a SyncLock block. The mechanism requires that the lock object remain unchanged.
I have a class that has two method in it, one calls a class which creates and executes a number of threads, the other is an event handler that handles an event raised when those threads complete (and then calls the first method again).
I understand that the method that handles the event runs in the thread that raised the event. So as such, I SyncLock a member variable that says how many threads are running and subtract one from it:
SyncLock Me ' GetType(me)
_availableThreads -= 1
End SyncLock
So I have a few questions:
Main Question: Should I be SyncLock'ing _availableThreads everywhere in the class - i.e in the method that creates the threads (which adds 1 when a thread is created)
Side Questions related to this question:
I'd usually SyncLock the current instance, but I've seen code that SyncLocks the type instead, so what is the difference between sync locking Me (Current Instance) and GetType(Me)?
Would there be a performance difference between the two? and is there anything smaller I'd be able to lock for the above that doesn't affect anything else - perhaps a separate 'padlock' object created for the sole purpose of locking things within a class?
Note: The sole purpose of _availableThreads is to control how many threads can run at any given time and the threads process jobs that can take hours to run.
Code:
Public Class QManager
Private _maxThreadCount, _availableThreads As Integer
Public Sub New(ByVal maxThreadCount As Integer)
Me.MaximumThreadCount = maxThreadCount
End Sub
Public Sub WorkThroughQueue()
//get jobs from queue (priorities change, so call this every time)
Dim jobQ As Queue(Of QdJobInfo) = QueueDAO.GetJobList
//loop job queue while there are jobs and we have threads available
While jobQ.Count > 0 And _availableThreads <= _maxThreadCount
//create threads for each queued job
Dim queuedJob As New QdJob(jobQ.Dequeue)
AddHandler queuedJob.ThreadComplete, AddressOf QueuedJob_ThreadCompleted
_availableThreads += 1 //use a thread up (do we need a sync lock here?)***************************
queuedJob.Process() //go process the job
End While
//when we get here, don't do anything else - when a job completes it will call this method again
End Sub
Private Sub QueuedJob_ThreadCompleted(ByVal sender As QdJobInfo, ByVal args As EventArgs)
SyncLock Me //GetType(me)
_availableThreads -= 1
End SyncLock
//regardless of how the job ended, we want to carry on going through the rest of the jobs
WorkThroughQueue()
End Sub
#Region "Properties"
Public Property MaximumThreadCount() As Integer
Get
Return _maxThreadCount
End Get
Set(ByVal value As Integer)
If value > Environment.ProcessorCount * 2 Then
_maxThreadCount = value
Else
value = Environment.ProcessorCount
End If
LogFacade.LogInfo(_logger, "Maximum Thread Count set to " & _maxThreadCount)
End Set
End Property
#End Region
End Class
You shouldn't SyncLock the instance or the type. You always want to SyncLock on a variable that is fully within the control of the class, and neither of those are. You should declare a private New Object and use that for your SyncLock.
Private lockObject as New Object()
...
SyncLock lockObject
...
End SyncLock
Unfortunately, you need to do a few things differently here.
First off, I'd recommend avoiding SyncLock, and using Interlocked.Increment and Interlocked.Decrement to handle changing _availableThreads. This will provide thread safety for that variable without a lock.
That being said, you still will need a SyncLock around every access to your Queue - if it's being used from multiple threads. An alternative, if you're using .NET 4, would be to change over to using the new ConcurrentQueue(Of T) class instead of Queue. If you use SyncLock, you should create a private object only accessible by your class, and use it for all synchronization.
You should be using the Interlocked class here, the Decrement() method to decrease the count. Yes, everywhere the variable is accessed.
Using SyncLock Me is as bad as SyncLock GetType(Me). You should always use a private object to lock on so nobody can accidentally cause a deadlock. The golden rule is that you cannot lock data, you can only block code from accessing data. Since the code is your private implementation detail, the object that holds the lock state must also be a private detail. Neither your object (Me) nor the Type of that object is private. Allowing other code to lock it by accident.
You can substitute the thread counter with Semaphore. If you use Semaphore you do not need to exit from while loop and neither it is necessary to call WorkThroughQueue() from ThreadCompleted event handler. Semaphore is thread safe so you can use it without locking.
http://www.albahari.com/threading/part2.aspx#_Semaphore