I think the confusion lies in what the lock keyword is doing. It is not saying only 1 thread can enter that section of code but it is saying 2 things:
- only one thread can enter this section of code who has thisLock
- Any other section which is locked with thisLock is also not to be allowed entry by any thread except this thread since this thread has thisLock.
What you are suggesting would only be doing the 1st one but not both. Look at this example:
class Account { decimal balance; private Object thisLock = new Object(); private Object thisLock2 = new Object(); public void Withdraw(decimal amount) { lock (thisLock) { if (amount > balance) { throw new Exception("Insufficient funds"); } balance -= amount; } // more code here but no locking necessary... lock(thisLock) { // only one thread can enter here who has thisLock } lock (thisLock2) { // If T1 (thread1) is working with thisLock, T2 can come here since it has nothing to do // with thisLock. } } public void AnotherOperation() { lock (thisLock) { // code here... } } public void YetAnotherOperation() { lock (thisLock) { // code here... } } }
When a thread, say T1, is doing the withdrawal part with the first lock, all other sections of the class with lock(thisLock) are not allowed entry by any other thread as well. However, the part with thisLock2 is allowed to be entered by other threads.
The best way to think of the lock keyword, at least it helped me when I was learning was to think of it as a hostage. In other words, when certain parts of the code are being executed it needs to take a hostage (thisLock) in your example. So once that thisLock is taken as hostage, no other thread can take it as hostage until that thread releases the hostage. Therefore, all other sections of code which also need the same hostage, become unavailable.
lockin the first place. The reasons why need thelockstatement needs to be passed a parameter are pretty clear, and the question is very valid if the author doesn't understand those reasons.