MySQL lock mechanism (table lock and row lock)


Definition of lock

A lock is a mechanism for a computer to coordinate multiple processes or threads to concurrently access a certain resource.

  • In the database, in addition to contention for traditional computing resources (such as CPU, RAM, I/O, etc.), data is also a shared resource. How to ensure the consistency and effectiveness of concurrent access to data is a must for all databases. problem.
  • Lock conflict is an important factor that affects the performance of concurrent access to the database. From this perspective, locks are particularly important for the database, and it is also more complicated.

Classification of locks

From the type of operation of the data is divided into: a read lock (shared lock) and a write lock (exclusive lock)

Read lock : For the same piece of data, the read operation of the data can be performed at the same time without being affected.

Write lock : Before the write operation is completed, other read and write operations will be blocked.

From operation is divided into a particle size of data: a table lock and row lock


Table lock

Table lock features

  • MylSAM引擎The use of table locks has low overhead, fast locking, no deadlocks, high locking strength, and the highest probability of lock conflicts.
  • Lowest concurrency
  • Does not support transactions

Simulation data

create table mylock (
id int not null primary key auto_increment,
name varchar(20) default ''
) engine myisam;

insert into mylock(name) values('a');
insert into mylock(name) values('b');
insert into mylock(name) values('c');
insert into mylock(name) values('d');
insert into mylock(name) values('e');

select * from mylock;

View database lock

SHOW OPEN TABLES in hanyxx; --查看数据库hanyxx中的表是否加锁
LOCK TABLE book read , phone write -- book表加读锁,phone表加写锁
--全部解锁
UNLOCK TABLES;

Table lock (read lock)

Host A adds a table lock (read lock) to the table

  • Both host A and other hosts can read the information in the table
  • Host A cannot read the information of other tables, but other hosts can read the information of other tables in the library
  • Host A cannot modify the locked table
  • Other hosts modify the table and will be blocked until the table lock (read lock) is released

Table lock (write lock)

Host A adds a table lock (write lock) to the table

  • Host A can read the table information, but when other hosts read it, it will enter a blocking state until the table lock (write lock) is released
  • Host A cannot read the information of other tables, but other hosts cannot read the information of this table, but can read the information of other tables
  • Host A can modify the table
  • Other hosts cannot modify the table and will be blocked until the table lock (write lock) is released

to sum up

Insert picture description here

The read lock does not block reads, only writes. But the write lock will block reading and writing.


Table lock analysis

Insert picture description here

Row lock (emphasis)

Row lock characteristics

  • High overhead, slow shackles, deadlocks
  • The smallest locking granularity, the lowest probability of lock conflicts, and the highest degree of concurrency

The biggest difference between InnoDB and MyISAM

  • Support affairs
  • Use row lock
    Insert picture description here

Problems caused by concurrent transactions

  • Dirty read
    Insert picture description here
  • Non-repeatable
    Insert picture description here
  • Phantom reading
    Insert picture description here

Transaction isolation level

Insert picture description here

  • View database isolation level
show variables like 'tx_isolation'; -- MySQL 5.7之前的版本
show variables like 'transaction_isolation'; -- MySQL 5.7之后的版本

MySQL database default isolation level:REPEATABLE-READ

Simulation data

-- 创建表
CREATE TABLE test_innodb_lock (a INT(11),b VARCHAR(16))ENGINE=INNODB;
-- 插入数据
INSERT INTO test_innodb_lock VALUES(1,'b2');
INSERT INTO test_innodb_lock VALUES(3,'3');
INSERT INTO test_innodb_lock VALUES(4, '4000');
INSERT INTO test_innodb_lock VALUES(5,'5000');
INSERT INTO test_innodb_lock VALUES(6, '6000');
INSERT INTO test_innodb_lock VALUES(7,'7000');
INSERT INTO test_innodb_lock VALUES(8, '8000');
INSERT INTO test_innodb_lock VALUES(9,'9000');
INSERT INTO test_innodb_lock VALUES(1,'b1');
-- 创建索引
CREATE INDEX test_innodb_a_ind ON test_innodb_lock(a);
CREATE INDEX test_innodb_lock_b_ind ON test_innodb_lock(b);
-- InnnDB事务自动提交,如果需要演示行锁,需要关闭自动提交
SET autocommit=0;

Basic demonstration of row lock

Insert picture description here

Row lock demonstration conclusion

If two clients modify the same record

  • After client A is modified, it is not submitted (not committed). At this time, client B's modification will be blocked
  • After client A is modified and submitted, client B will modify it again, it will not be blocked
  • If two clients modify different record lines respectively, they will not be blocked

Index failure

Index is invalid, row lock becomes table lock (use varchar type without single quotation mark to make index invalid)

When the index is invalid, even if multiple clients are not operating on the same record, if it is not submitted, other clients will enter the blocking state

So to avoid index failure

Why does index invalid row lock change table lock

  • InnoDB row-level locks are implemented by locking the index items on the index. InnoDB row-level locks use row-level locks only when data is retrieved through index conditions.
  • Otherwise, InnoDB uses table locks when querying without index (primary key) conditions, InnoDB uses table locks instead of row locks.

Gap lock

What is a gap lock

Insert picture description here

Gap lock demo

Insert picture description here

Insert picture description here

The hazards of gap locks

Insert picture description here

Insert picture description here

Interview question: how to lock a row

Insert picture description here

Row lock analysis

InnoDB_row_lock

  • Analyze row lock competition by checking the InnoDB_row_lock state variable
show STATUS like 'innodb_row_lock%'; -- 查看InnoDB_row_lock状态变量

Insert picture description here

Field description

Field Description
Innodb_row_lock_current_waits The number of locks currently waiting
Innodb_row_lock_time(important) How long has the system been locked since the start of the system
Innodb_row_lock_time_avg(important) Average time per lock
Innodb_row_lock_time_max The longest lock time
Innodb_row_lock_waits(important) Since the system was started, how many times has it been locked?

Optimization suggestion

  • Try to make data retrieval complete through indexes, avoid no indexes, and upgrade row locks to table locks
  • Design the index reasonably and reduce the scope of the lock
  • Reduce retrieval conditions as much as possible to avoid gap locks
  • Control the size of the transaction as much as possible, reduce the amount of locked resources and the length of time
  • Use a low-level transaction isolation level as much as possible

to sum up

Insert picture description here

Page lock (supplement):

  • The overhead and locking time are between table locks and row locks, and deadlocks will occur
  • Locking granularity is between table locks and row locks, with general concurrency

Guess you like

Origin blog.csdn.net/single_0910/article/details/113892413