Why do I need a backup lock object?

Out of curiosity, I looked at the lock keyword on MSDN:

 class Account { decimal balance; private Object thisLock = new Object(); public void Withdraw(decimal amount) { lock (thisLock) { if (amount > balance) { throw new Exception("Insufficient funds"); } balance -= amount; } } } 

In the above example, thisLock used with the lock keyword. Why is this necessary? He seems to have no other goals. Why not just use the lock keyword yourself?

+4
source share
3 answers

The object used to lock is not redundant. The object acts as a token, which is used to implement a simple synchronization protocol: everyone who has a lock is granted access to the blocked code. Everyone else must wait until the lock is released.

Without an object, it would be impossible to have different tokens, and all synchronization would rely on one internal token. That would not be very effective.

0
source

lock keyword cannot exist on it; it always accepts a parameter that will act as a semaphore (synchronizing object), allowing only one thread to continue.

http://www.albahari.com/threading/part2.aspx#_Locking

Only one thread can lock the synchronizing object (in this case, thisLock) at a time, and any competing threads are blocked until the lock is released. If more than one thread is discussing a lock, they are queued on a โ€œready-made queueโ€ and provide the lock in the first place (the caveat is that the nuances in the behavior of Windows and the CLR mean that queue justice can sometimes be violated).

+4
source

There are several aspects to this:

  • lock statements require an object reference as an identifier. It must have what identifies this lock and separates it from any other locks that may exist in the code.

  • The data you protect is not a reference type, so you need to use something else as a lock identifier.

  • It is recommended that you use a private object that is used only as a lock identifier, even if you could use the data as an identifier. Thus, there is no reason to ever set a link outside the class, as this will open for possible deadlocks if it were used in a lock outside the class.

0
source

Source: https://habr.com/ru/post/1487911/


All Articles