Locking mechanism and InnoDB lock algorithm

1. Locks used by MyISAM and InnoDB storage engines:

  • MyISAM uses table-level locking.
  • InnoDB supports row-level locking and table-level locking, the default is row-level locking

2. Comparison of table-level locks and row-level locks:

  • Table-level lock: The lock with the largest locking granularity in MySQL. It locks the entire table of the current operation. It is simple to implement, consumes less resources, locks quickly, and does not cause deadlock. It has the largest locking granularity, the highest probability of triggering lock conflicts, and the lowest concurrency. Both MyISAM and InnoDB engines support table-level locks.
    Row-level lock: A lock with the smallest lock granularity in MySQL, which only locks the row of the current operation. Row-level locks can greatly reduce conflicts in database operations. Its locking granularity is the smallest, and the concurrency is high, but the overhead of locking is also the largest, and the locking is slow, and deadlocks will occur.

3. There are three lock algorithms for the InnoDB storage engine:

  • Record lock: the lock on a single row record
  • Gap lock: gap lock, lock a range, excluding the record itself
  • Next-key lock: record+gap locks a range, including the record itself

Related knowledge points:

  • Innodb uses next-key lock for row queries
  • Next-locking keying in order to solve the Phantom Problem
  • When the query index contains unique attributes, downgrade next-key lock to record key
  • The purpose of Gap lock design is to prevent multiple transactions from inserting records into the same range, which will lead to phantom reading problems.
  • There are two ways to explicitly close the gap lock: (except for foreign key constraints and uniqueness checks, only record lock is used in other cases) A. Set the transaction isolation level to RC B. Set the parameter innodb_locks_unsafe_for_binlog to 1

Guess you like

Origin blog.csdn.net/qq_43518425/article/details/115291901