techiall / Blog

🍋 [My Blog] See discussions
https://github.com/techiall/Blog/discussions
MIT License
8 stars 1 forks source link

mysql 意向锁 #62

Open techiall opened 4 years ago

techiall commented 4 years ago

以下内容来自有赞的技术文章 Mysql锁:灵魂七拷问 https://tech.youzan.com/seven-questions-about-the-lock-of-mysql/


(个人觉得写的不错,就直接引用了


假设事务 A 锁住了表T里的一行记录,这时候,你执行了一个 DDL 语句,想给这张表加个字段,这时候需要锁表吧?但是由于表里有一行记录被锁住了,所以这时候锁表时会 block。

那 Mysql 在锁表时,怎么判断表里有没有记录被锁住呢?

最简单暴力的,遍历整张表,遍历每行记录,遇到一个锁,就说明表里加锁了。

这样做可以,但是很傻,性能很差,高性能的 Mysql,不允许这样的做法存在。

Mysql 会怎么做呢?

行锁是行级别的,粒度比较小,好,那我要你在拿行锁之前,必须先拿一个假的表锁,表示你想去锁住表里的某一行或者多行记录。

这样,Mysql 在判断表里有没有记录被锁定,就不需要遍历整张表了,它只需要看看,有没有人拿了这个假的表锁。

这个假的表锁,就是我们常说的,意向锁。

Intention locks are table-level locks that indicate which type of lock (shared or exclusive) a transaction requires later for a row in a table