Introduction to MySQL locks

Introduction

  • When the database has concurrent transactions, data inconsistencies may occur. At this time, some mechanism is needed to ensure the order of access, and the lock mechanism is such a mechanism.

1. Classification of MySQL locks

Insert picture description here

1.1 Divided by lock granularity

  • Divided into: the
    smaller the granularity of row locks, page locks, and table locks , the lower the probability of lock conflicts, and the higher the degree of concurrency that can be achieved; however, the overhead for locks is relatively large, and the locking will be slower and prone to deadlock. lock.

1.1.1 Row Lock

  • Row-level lock is the finest type of lock in Mysql, which means that only the row of the current operation is locked.

  • Row-level locks can greatly reduce conflicts in database operations. The locking granularity is the smallest, but the locking overhead is also the largest. Row-level locks are divided into shared locks and exclusive locks.

  • Features
    High overhead and slow locking;
    deadlock will occur; the
    smallest locking granularity, the lowest probability of lock conflicts, and the highest concurrency.

  • Three types of row locks

1、Record Lock 单个记录上的锁
对索引项加锁,如果innodb引擎的表在建立的时候 没有设置任何索引 那么这时候对InnoDB存储引擎会用隐性的主键来进行锁定。

2、Gap Lock 间隙锁
对索引项之间的间隙加锁,锁定一个范围,但不包含记录本身
设计目的: 为了解决幻读,利用这种锁技术,锁定的不是单个值,而是一个范围。

3、Next-key lock
则是前面两种的组合,对索引项以其之间的间隙加锁。Gap Lock + Record Lock,锁定一个范围,并且锁定记录本身
只有在可重复读或以上的隔离级别下的特定操作才会取得gap lock或者 next-key lock,在select update delete时,除了基于唯一索引的查询之外,其他索引都会获取gap lock 或者 next-key lock,即锁住扫描的范围。

Insert picture description here

1.1.2 Page Lock

  • Page-level locks are a type of lock in MySQL whose locking granularity is between row-level locks and table-level locks.
    Table-level locking is fast, but there are many conflicts, and row-level conflicts are few, but the speed is slow. Therefore, a compromised page level is taken, and a set of adjacent records is locked at a time.

  • Features The
    overhead and lock time are between table locks and row locks;
    deadlocks will occur; the
    locking granularity is between table locks and row locks, and the concurrency is general

  • Blocking granularity is small:
    benefits: the less the amount of locked data, the smaller the possibility of lock contention, the higher the degree of concurrency of the
    system ; the disadvantages: the system overhead is large (locking, releasing locks, checking lock status all need to be consumed Resources)

1.1.3 Table lock

  • Table lock is the lock with the largest locking granularity in MySQL. It means to lock the entire table of the current operation. It is simple to implement and consumes less resources. It is supported by most MySQL engines. The most commonly used MYISAM and INNODB both support table-level locking.

  • Table-level locks are divided into table shared read locks (shared locks) and table exclusive write locks (exclusive locks).

  • Features
    Low overhead and fast locking;
    no deadlock;
    large locking granularity, the highest probability of lock conflicts, and the lowest concurrency.

1.2 Distinguish from the perspective of database management

  • Divided into: shared locks and exclusive locks, namely read locks and write locks-"MySQL common lock types

1.2.1 Shared lock/S lock

  • Also called read lock or S lock
    . The resources of the shared lock can be read by other users, but cannot be modified;
    when selecting, the object will be locked with a shared lock;
    when the reading is completed, the lock will be released to ensure that the data is being read Will not be modified when fetching.
mysql> lock table xxx read;
mysql> unlock table;
  • Scenario: It is equivalent to having multiple keys for the same door.

  • Adding lock in share mode after the execution statement means adding a shared lock to some resources.

mysql> SELECT * FROM table_name WHERE ... LOCK IN SHARE MODE;  #共享锁
  • The reason for the deadlock in the shared lock: When multiple transactions obtain a read lock on the same data, a deadlock may occur.

1.2.2 Exclusive lock/X lock

  • Also called exclusive lock, write lock or X lock.
    Exclusive lock, the locked data can only be used by the locked transaction;
    other transactions cannot query and operate on the locked data.
mysql> lock table xxx write;
mysql> unlock table;
  • When a transaction adds an X lock to the data, only the transaction is allowed to read and modify the data, and other transactions cannot add any locks to the data;
SELECT * FROM table_name WHERE ... FOR UPDATE;   # 排它锁

1.3 Distinguish from the perspective of programmers

  • Locks can be divided into optimistic locks and pessimistic locks.

1.3.1 Optimistic Locking

  • Optimistic locking believes that concurrent operations on the same data will not always occur, and it is optimistic, which is a small probability event; there is no need to lock the data every time, that is, it does not use the database's own locking mechanism, but implements it through the program;

  • In the program, we can use the version number mechanism or the time stamp mechanism to achieve; in fact, it is the program level control, there will be no deadlock problem, but it cannot prevent the database operation outside the program.

  • The main way to achieve:

1、版本号机制:
新增version字段,第一次读取的时候会获取version的值,然后对数据进行更新和删除操作时,会进行版本号的比对;
如果版本号一致,则修改数据,并将版本号+1;如果版本号不一致 则修改失败。

2、时间戳机制:
其道理和版本号一样。

1.3.2 Pessimistic lock

  • In fact, it is a kind of thought. A conservative attitude towards data modification by other transactions will be realized through the database's own lock mechanism to ensure the exclusivity of data operations!
  • If you hold a pessimistic attitude towards data conflicts, you think there will be conflicts, so you will lock the data every time the data is read; all subsequent read operations need to wait;
  • Implementation at the database level prevents all database operations.

2. Common deadlock problems

  • Necessary conditions: mutually exclusive, occupy and wait, not forcibly occupy, and cyclically wait.

  • The method to solve the deadlock: The
    best way is to prevent the deadlock from happening.

Some details to note:

1、不要将无关的操作放进事务里,小事务发生死锁的概率很低;
2、如果不同的程序会同时操作多个表,应尽量约定以相同的顺序来访问表,这样事务就会形成良好的定义的查询;
3、尽量按照索引去查数据,范围查找增加了锁的可能性;
4、对于非常容易产生死锁的业务部分,可以尝试升级锁的粒度;
5、更新表时,尽量使用主键更新;
6、设置锁等待超时参数,通过设置 innodblockwait_timeout 参数,设置合理的等待阈值;在高并发的业务中,尽量
将该值设置的小一点,避免大量事务等待,占用系统资源,造成严重的性能开销;
7、Innodb提供了wait-for graph算法来主动进行死锁检测,我们可以通过innodbdeadlockdetect = on 打开死锁检测。

Reference link: https://juejin.cn/post/6901876623184920584

Guess you like

Origin blog.csdn.net/weixin_42449832/article/details/112609697