Multiple blocks of code blocked by the same object

If I have something like this:

private readonly object objectLock = new object(); public void MethodA() { lock(objectLock) { //do something } } public void MethodB() { lock(objectLock) { //do something } } 

If I have 2 threads and both come in at the same time, the 1st thread calls MethodA and the second Method B. Whatever it is first and blocks objectLock, I assume that the other thread sits there until objectLock is no longer blocked.

+7
source share
5 answers

Yes, your explanation is correct - if the lock has not already been completed (in this case, both threads are waiting, and an arbitrary one gets the lock as soon as it is unlocked).

(A little offtopic) I would advise against blocking all methods if they do something non-trivial. Try to keep the "blocking" section of the code as small and as fast as possible.

+5
source

It is right.

However, the Lock object (or object) is not locked; this is code lock.

Think of an object that is passed to the lock keyword as a key that unlocks several doors but only provides access to one room at a time.

+4
source

You're absolutely right! But be careful with locks. Locks may make you be thread safe (which means there are no errors while accessing simultaneously), but it takes much more effort for your program to really benefit from working in a multi-core system.

+1
source

yes, you are right, as Monitor.Enter and Monitor.Exit are called on the same objectLock behind the scene. remember its code block, which is not synchronized by objectLock.

0
source

You're right. If this is undesirable, consider that:

 lock(objectLock) { //do something } 

It is equivalent to:

 Monitor.Enter(objectLock); try { //do something } finally { Monitor.Exit(objectLock); } 

You can replace this as follows:

 if(Monitor.TryEnter(objectLock, 250))//Don't wait more than 250ms { try { //do something } finally { Monitor.Exit(objectLock); } } else { //fallback code } 

It is also worth looking at TryEnter() overloads and other synchronization objects such as ReaderWriterLockSlim .

0
source

All Articles