It allows multiple threads to read a resource at the same time, but requires the thread to expect an exclusive lock to write to the resource.
Rules:
- Multiple readers can share a resource at the same time. If you have a read lock, you can safely acquire another read lock. Maximum number of shared locks 1111 1111 1111 1111
- If you have a read lock, you CANNOT get a write lock
- If you have a write lock, you CANNOT get a read lock on any other thread.
- The reader can access the resource if there are no active authors in any other thread.
- If you have a write lock, you can purchase another write lock on the same thread. The maximum number of exclusive locks that can own 1111 1111 1111 1111
- A writer can access a resource when another reader or writer (from another thread) is not active.
- Prefers authors over readers. That is, if a writer expects a lock, no new readers from another thread can access the resource. Existing readers can continue to use the resource until they release the lock. This prevents the so-called "hungry writer."
- Allows you to switch from write lock to read lock, by acquiring write lock, then read lock and release write lock. However, updating from read lock to write lock is not possible.
The internal lock state (c) is maintained by the value int. In this case, since we have read and write locks, it is logically divided into two shorts: the lower one representing the lock (write) lock counter, and the upper shared counter (reader).
Assuming the current lock state is c = xxxx xxxx xxxx xxxx yyyy yyyy yyyy yyyy then the number of reader locks is the upper bits xxxx xxxx xxxx xxxx
The number of write locks is the least significant bits of yyyy yyyy yyyy yyyy
source share