Sync Locks

mbb

Well-known member
Joined
Jun 3, 2009
Messages
52
Programming Experience
10+
Hello,

I am considering a piece of code that will manage access to a collection object from multiple threads - add, update, remove, clear.

OK ... so I have put a sync lock within each method, but what is not clear from the MS documentation is exactly how the sync lock is behaving.

Is it locking the piece of code it wraps? Or is it locking the object? And if it is locking the object a private static object should lock out any code locked on the object within all instances of the object? i.e. if an add operation is underway, an update, delete or clear will wait for the lock to be released.

Finally, if I have multiple threads contending for the sync lock, how is the release managed? First come, first serve? random (from my p.o.v)? Is there a chance that two separate threads could blunder into 'locked' code simulataneously?

Thanks
 
The SyncLock block defines a "critical section", which is a block of code that can only be executed on a single thread at a time. There's absolutely no way that two threads can execute the same critical section at the same time. The reason that you lock ON an object is that you can actually link more than one SyncLock block. If two SyncLock blocks lock on the same object then they act as one critical section, i.e. if one thread enters one of the SyncLock blocks then no thread can enter either of the SyncLock blocks. I say "no thread" rather than "no other thread" because, particularly with linked SyncLock blocks, you can end up with a deadlock where a single thread can't enter a second SyncLock block because it has already entered another one that locks on the same object. The thread would therefore be deadlocked against itself.

If multiple threads are queued at a SyncLock and the lcok is released, I would guess that they would enter in the order they arrived but I've never specifically heard or seen that that happens. It wouldn't be too hard to test though.
 
Thanks, this is exactly what I needed to know.

I can use the sync lock to protect all critical operations on the collection then and I'll try very hard not to deadlock. ;)
 
Back
Top