In ReentrantReadWriteLock documentation it is said:
writer can acquire the read lock, but not vice-versa
If I understand correctly it means that from the same thread you can execute:
//thread1
lock.writeLock().lock()
lock.readLock().lock()
print("this line executes")
This makes sense: if you already locked write no other thread can enter the locked code. But if you locked read, why can't you enter the write block in the same thread if no other thread make read lock? So this doesn't work:
//thread1
lock.readLock().lock()
lock.writeLock().lock()
print("this line doesn't execute")
Why do you have to unlock the read before locking write in the same thread?
ReentrantReadWriteLock doesn't mean that the normal rules locking are not followed.
If a thread acquired a lock for reading purpose, it expects the value of the target data not to change for the duration of the lock. Having otherwise would prevent repeatable-reads. Conceptually, if you let a thread (the same or another) acquire a write lock when a read lock is out, you are breaching that rule.
If a thread acquired a lock for writing, it implicitly has reading rights as well, so acquisition of a read-lock can be granted because it doesn't really breach the contract of the lock (if I can write, I can read) nor the expectations of the lock holder (I locked for writing so I am the only one that can read or write now).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With