VB.NET Do I need several SyncLocks if I want to block several things?

VB.NET 2010, .NET 4

Hello to all,

My question is: Imagine that I have two List (Of T) objects and a subroutine in a multi-threaded environment that modifies both of these objects. I don't understand locks very well, so I'm not sure if I can just do:

SyncLock CType(List1, IList).SyncRoot List1.Clear() List2.Clear() End SyncLock 

or should I:

 SyncLock CType(List1, IList).SyncRoot SyncLock CType(List2, IList).SyncRoot List1.Clear() List2.Clear() End SyncLock End SyncLock 

? Any insight? Am I even on the right track? Any comments would be appreciated.

Thanks a lot, Brian

+1
list multithreading locking
source share
2 answers

Firstly, it’s a bad practice to block a non-private object, because something else can block it, and then things go down, instead block a private member object, something like

 Class Class1 Private lockObject as New Object Public Sub Clear() SyncLock lockObject ... End Synclock End Sub End Class 

Now, for the actual question: if every operation you do does not change both lists (doubtful), you should have one lock on the list. Although you can use one lock object to indicate "I'm doing something with a list", it makes no sense to block a method in another thread that does not work in the same list as yours and will just slow down everything.

So, in short: use one lock object for each set of locks (locks for working in list1, locks for list 2, etc.). This is a bit more code for sections running on both lists, but the code will be more efficient.

As well as a general note: hold the lock as little time as possible. The less time you spend in the castle, the less likely it is that another stream will come and be blocked until you finish.

The MSDN page on SyncLock can also be read; it contains this information and a few examples. And @BasicLife is correct, always make sure that locks are in the same order everywhere.

And the general rule in the whole structure, if you do not refer to the static member of the class, unless otherwise specified, it is not thread safe. Therefore, when you work in lists, you need to block when you add, delete, clear or list the list, I am sure that there are others, but they are the most common.

+7
source share

To expand Matt's answer, make sure you lock objects in the same order if you need multiple locks

If in Method1 you do:

 Lock List 1 Lock List 2 Release 2 Release 1 

and in Method2 you will do:

 Lock List 2 Lock List 1 Release 1 Release 2 

Then you can get a deadlock situation where if both methods are called at the same time using different threads, you can get this:

 thread 1 on Method1 locks list 1 thread 2 on Method2 locks list 2 thread 1 on Method1 waits until list 2 is released thread 2 on Method2 waits until list 1 is released Threads 1 and 2 are now deadlocked and eventually one or both will be killed off 
+4
source share

All Articles