First, A is not locked but rather threads become locked at the call of "lock()". There's no hidden locking mechanism here. A simple check is done which verifies that no other thread is currently holding the lock. If it is locked, it waits until it is unlocked, otherwise it continues executing the code.
You're right that generally speaking, locking code should be avoided unless absolutely necessary and when you do lock, it must hold a lock for as little time as possible to avoid potential bottlenecks. A good rule of thumb for knowing when code should be locked is to ask yourself the following questions:
- At any step in this process, would I care if it got interrupted? (imagine the power to the computer failing and not all your code gets executed.. would it be a problem?)
- If my program kept re-executing code due to some processor error, local variables aside, would there be some sort of risk of tampering with the end result in the previous execution?
If you answer yes to either, congratulations! You've found code you need to lock.
Typically there are two types of locks: read and write locks. If you just see "lock()" and "unlock()", what you're seeing is a write lock. A write lock is the most severe form of lock and it blocks threads regardless of what you're executing. Sometimes you may not even need to perform an operation, just simply check to see if you need to, yet you don't want to read data that may have since been modified by another thread, so you have to keep it in a lock. For this, you need a read lock. Read locks are always used in combination with a write lock. Typically you see a read lock immediately and some sort of check. If the check passes, you place a write lock to ensure that no thread can enter the read lock section until you're sure that it is in a consistent state.
If you write it correctly, you need not know whether or not a thread is locked just like you don't know when writing to a file will cause a program to block while it's being used by another program.
If that didn't answer your question, then perhaps I didn't quite follow what you were asking.