I think the confusion is what the keyword lock does. This does not say that only 1 thread can enter this section of code, but it says 2 things:
- only one thread can enter this section of code that has thisLock
- Any other section that is locked by thisLock should also not be allowed to enter any stream other than this stream, since this stream has thisLock.
What you offer will do only one thing, but not both. Take a 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; }
When a stream, say T1, does part of the output with the first lock, all other sections of the class with a lock (thisLock) are not allowed to write to any other thread. However, the part with this Lock2 is allowed for input by other threads.
The best way to think of a blocking keyword, at least it helped me when I was studying, was to think of it as a hostage. In other words, when certain parts of the code are executed, your example requires a capture (thisLock). Therefore, when this box is considered a hostage, no other thread can consider it a hostage until this thread releases the hostage. Therefore, all other sections of the code, which also need the same hostage, become inaccessible.
source share