天天看点

MySQL5.7 : 对隐式锁转换的优化

mysql5.7 : reduce lock_sys_t::mutex contention when converting implicit lock to an explicit lock

worklog: http://dev.mysql.com/worklog/task/?id=6899

rev: http://bazaar.launchpad.net/~mysql/mysql-server/5.7/revision/5743

背景:

1.什么是隐式锁

所谓的隐式锁,可以理解成一个记录标记,在内存的锁对象hash中是不存在的。但我们在更新数据块时,会进行如下操作:

#对于聚集索引,每次更改或插入记录会同时写入对应的事务id和回滚段指针

#对于二级索引,每次更改/插入二级索引记录,会更新二级索引页的最大事务id。

我们知道,innodb在插入记录时,是不加锁的。如果事务a插入记录rec1,且未提交时。事务b尝试update rec1,这时候事务b会去判断rec1上保存的事务id是否活跃,如果活跃的话,那么就 “帮助” 事务a 去建立一个锁对象,加入到hash中,然后自身进入等待事务a状态,也就是所谓的隐式锁转换为显式锁。

该worklog主要优化了该转换的过程

原始逻辑

参考函数lock_rec_convert_impl_to_expl

0.找到修改或插入当前记录的事务id (记做trx_id, 不持有锁),如果不是活跃的事务id,不做操作,退出函数

1. acquire the lock_sys_t::mutex

2. (trx_rw_is_active)

acquire the trx_sys_t::mutex

scan the trx_sys_t::rw_trx_list for trx_id_t (only rw transactions can insert)

release the trx_sys_t::mutex

return handle if transaction found

3. if handle found then

do an implicit to explicit record conversion

endif

4. release the lock_sys_t::mutex

可以看到,在该操作的过程中,全程持有lock_sys mutex,持有锁的原因是防止事务提交掉.当读写事务链表非常长时(例如高并发写入时),这种开销将是不可接受的。

优化后的逻辑

if handle found then

acquire the trx_t::mutex

increment trx_t::n_ref_count ——增加计数,表示对这个事务进行隐式锁转换

release the trx_t::mutex

acquire the lock_sys_t::mutex

release the lock_sys_t::mutex

decrement trx_t::n_ref_count ——完成隐式转换,重置计数

这里实际上在查找当前记录上的活跃事务id时,直接返回的是其事务对象,而不是事务id

在事务commit时进行检查 (函数lock_trx_release_locks)

if trx_t::n_ref_count > 0

while (trx_t::n_ref_count > 0) ———>当前正在做隐式到显式的锁转换

sleep/delay

acquire the trx_t::n_ref_count

end while

通过该修改,我们可以在获取活跃事务对象的时候无需持有lock sys mutex。在低并发下,可能没有太多收益,但在高并发下,读写事务链表较长时,可能会影响到性能。

但该特性带来的额外开销是,事务在commit时需要检查ref count,理论上锁转换过程应该很快.

继续阅读