问题
Following up on https://stackoverflow.com/a/16553083/14731...
I understand that it is important to maintain a consisting locking order for tables in order to reduce the frequency of deadlocks, and that this affects both UPDATE
and SELECT
statements [1]. But, does the same hold true for read-only rows?
If a row is populated once at initialization time and no one modifies it ever again, does it really matter what order we access it?
Given two transactions: T1, T2 and two read-only rows R1, R2
T1 reads R1, then R2 T2 reads R2, then R1
Can the transactions deadlock, even if I use SERIALIZABLE transaction isolation?
[1] If transaction isolation is REPEATABLE_READ
, T1 SELECT
s R1, R2 while T2 UPDATE
s R2, R1 a deadlock may occur.
CLARIFICATION: This question is not RDBMS-specific. I am under the impression that no implementation can deadlock on read-only rows. If you have a counter-example (for a concrete vendor), please post an answer demonstrating as much and I will accept it. Alternatively, post a list of all concrete implementations that you can prove will not deadlock (and the most complete list will get accepted).
回答1:
This question is impossible to answer for all possible RDBMS's because the locking strategy is an implementation detail. That said, useful RDBMS's will share some common characteristics:
For SELECT
statements without hints applied (FOR UPDATE
, WITH (UPDLOCK)
, ...) any reasonable RDBMS will not take write-locks. It might take read-locks. Indeed, at least SQL Server does so for SERIALIZABLE
except on Hekaton tables.
Read-locks never conflict. No deadlock is possible if only reads are being executed.
Read-only rows can however cause deadlocks even if they are never written to. In SQL Server,
UPDATE T SET SomeCol = 1 WHERE ID = 10 AND SomeCol = 0
will take an U-lock on the row with ID 10. If SomeCol is not 0 the lock will be released immediately and nothing will be written. But the U-lock is a lock type that can potentially conflict and lead to a deadlock. Had the row with ID 10 not been present no deadlock would have been possible.
来源:https://stackoverflow.com/questions/25676116/can-read-only-rows-trigger-database-deadlocks