What are shared and exclusive locks?
EasyConceptConcurrency Control & Locking
Answer
A lock is a marker that a transaction places on a data item to control how other transactions may access it.
- Shared (S) lock: taken for reading. Many transactions can hold S locks on the same item at the same time.
- Exclusive (X) lock: taken for writing. Only one transaction can hold it, and no other transaction can hold any lock on that item meanwhile.
- A request that is not compatible with the locks already held must wait until they are released.
- Locks have a granularity: row, page or table. Row locks allow more concurrency, while table locks have less overhead.
Example: The lock compatibility matrix:
S held X held
request S yes no
request X no no
In MySQL 8 and PostgreSQL, SELECT ... FOR SHARE takes a shared row lock and SELECT ... FOR UPDATE takes an exclusive one:
SELECT * FROM seats WHERE id = 7 FOR UPDATE; -- others must wait to change seat 7