Search code examples
c#multithreadingconcurrencylocking

Meaning of object passed to the lock statement


Can someone clarify me:

The statements inside the lock will be locked no one can go through unless it's finished and release the lock. Then what is the object inside the lock used for?

lock (obj) 
{ 
    //statement 
}

Does that mean the obj is being locked and cannot be used from anywhere else unless the lock has done his work?


Solution

  • I've made a very simple class to illustrate what the object in the lock is there for.

    public class Account
    {
        private decimal _balance = 0m;
        private object _transactionLock = new object();
        private object _saveLock = new object();
    
        public void Deposit(decimal amount)
        {
            lock (_transactionLock)
            {
                _balance += amount;
            }
        }
    
        public void Withdraw(decimal amount)
        {
            lock (_transactionLock)
            {
                _balance -= amount;
            }
        }
    
        public void Save()
        {
            lock (_saveLock)
            {
                File.WriteAllText(@"C:\Balance.txt", _balance.ToString());
            }
        }
    }
    

    You'll notice that I have three locks, but only two variables.

    The lines lock (_transactionLock) mutually lock the regions of code to only allow the current thread to enter - and this could mean that the current thread can re-enter the locked region. Other threads are blocked no matter which of the lock (_transactionLock) they hit if a thread already has the lock.

    The second lock, lock (_saveLock), is there to show you that the object in the lock statement is there to identify the lock. So, if a thread were in one of the lock (_transactionLock) statements then there is nothing stopping a thread to enter the lock (_saveLock) block (unless another thread were already there).