show variables like '%innodb_lock_wait%' set innodb_lock_wait_timeout=600 开启两个会话。
session A id=8: begin select count(1) from peoples where age>30 for update; session B id=5: begin insert into peoples(age) values(31) show processlist 找到连接的id。
***************************[ 1. row ]*************************** Id | 3 User | root Host | 172.17.0.1:60542 db | test Command | Query Time | 0 State | starting Info | show processlist ***************************[ 2. row ]*************************** Id | 5 User | root Host | 172.17.0.1:60546 db | test Command | Query Time | 394 State | update Info | insert into peoples(age) values(31) ***************************[ 3. row ]*************************** Id | 8 User | root Host | 172.17.0.1:60552 db | test Command | Sleep Time | 396 State | Info | <null> 事务 select * from information_schema.innodb_trx G 查看事务执行情况。
innodb 监视器 show engine innodb status LIST OF TRANSACTIONS FOR EACH SESSION: ---TRANSACTION 422032240994144, not started 0 lock struct(s), heap size 1136, 0 row lock(s) ---TRANSACTION 457240, ACTIVE 394 sec inserting mysql tables in use 1, locked 1 LOCK WAIT 5 lock struct(s), heap size 1136, 7 row lock(s), undo log entries 1 MySQL thread id 5, OS thread handle 140556966967040, query id 105 172.17.0.1 root update insert into peoples(age) values(31) ------- TRX HAS BEEN WAITING 165 SEC FOR THIS LOCK TO BE GRANTED: RECORD LOCKS space id 131 page no 4 n bits 72 index idx_peoples_age of table `test`.`peoples` trx id 457240 lock_mode X locks gap before rec insert intention waiting Record lock, heap no 4 PHYSICAL RECORD: n_fields 2; compact format; info bits 0 0: len 4; hex 80000023; asc #;; 1: len 4; hex 00000007; asc ;;
------------------ ---TRANSACTION 457239, ACTIVE 407 sec 3 lock struct(s), heap size 1136, 5 row lock(s) MySQL thread id 8, OS thread handle 140556966696704, query id 104 172.17.0.1 root MySQL thread id 5 正在准备上插入意向锁,插入意向锁本质上是加间隙锁,是为了保证最大并发插入,不相关的行插入不受到互斥。thread id 5 需要保证在插入前加上间隙锁,主要是防止并发插入带来的一致性问题。