简体   繁体   中英

Why is a redundant lock object needed?

Out of curiosity was looking 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 example above the object thisLock is used with the lock keyword. Why is this needed? It doesnt seem to have any other purpose. Why not just have the lock keyword by itself?

lock keyword cannot exist on it's own, it always takes a parameter which will act as a semaphore (synchronizing object), allowing only one thread to proceed.

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 contending threads are blocked until the lock is released. If more than one thread contends the lock, they are queued on a “ready queue” and granted the lock on a first-come, first-served basis (a caveat is that nuances in the behavior of Windows and the CLR mean that the fairness of the queue can sometimes be violated).

There are several aspects here:

  • The lock statements needs an object reference as identifier. It has to have something that identifies this lock and separates it from any other locks that can exist in the code.

  • The data that you are protecting isn't a reference type, so you need something else to use as the identifier for the lock.

  • It's recommended to have a private object that is only used as identifier for the lock, even if it would be possible to use the data iself as identifier. That way there is no reason to ever expose the reference outside the class, as that would open up for possible deadlocks if it was used in a lock outside the class.

The object used for locking isn't redundant. The object acts as a token, which is used to implement a simple synchronization protocol: Whoever holds the lock is granted access to the locked code. All others have to wait until the lock is released.

Without an object it would not be possible to have different tokens and all synchronization would rely on a single internal token. That would not be very effective.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM