MySQL半一致性读原理解析-从源码角度解析

1、什么是半一致性读

A type of read operation used for UPDATE statements, that is a combination of read committed and consistent read. When an UPDATE statement examines a row that is already locked, InnoDB returns the latest committed version to MySQL so that MySQL can determine whether the row matches the WHERE condition of the UPDATE. If the row matches (must be updated), MySQL reads the row again, and this time InnoDB either locks it or waits for a lock on it. This type of read operation can only happen when the transaction has the read committed isolation level, or when the innodb_locks_unsafe_for_binlog option is enabled.

就是发生在update语句中。在RC隔离级别或者innodb_locks_unsafe_for_binlog被设置为true,并发时,如果update的记录发生锁等待,那么返回该记录的prev 版本(在返回前会将锁等待的这个lock从trx中删除掉),到mysql层进行where判断,是否满足条件。如果满足where条件,那么再次进入innodb层,真正加锁或者发生锁等待。

这样做的好处是:减少同一行记录的锁冲突及锁等待;无并发冲突时,直接读取最新版本加锁,有冲突时,不加锁,读取prev版本不需要锁等待。

缺点:非冲突串行话策略,对于binlog来说是不安全的。只能发生在RC隔离级别和innodb_lock_unsafe_for_binlog下。

2、原理
MySQL半一致性读原理解析-从源码角度解析
3、讲解

1)半一致性读需要mysql层和innodb层配合使用。

2)mysql_update函数中,默认都会调用try_semi_consistent_read在RC或innodb_lock_unsafe_for_binlog下加上试图半一致性读标签:prebuilt->row_read_type = ROW_READ_TRY_SEMI_CONSISTENT。真正执行半一致性读是由innodb层决定。

3)半一致性读的条件:该记录发生锁等待;必须是全表扫描 && 该索引是二级索引

4)半一致性读时,构建prev版本,然后调用函数lock_trx_handle_wait将锁等待从trx中删除。

5)返回prev rec前,会将置成半一致性读标签:prebuilt->row_read_type = ROW_READ_DID_SEMI_CONSISTENT

6)返回到mysql层,会进行where判断。如果匹配,那么会再次进入innodb层,由于prebuilt->row_read_type == ROW_READ_DID_SEMI_CONSISTENT,此时不再走半一致性读判断的流程,直接进入加锁或锁等待。

5)这里update有个优化:innodb层如果执行计划是索引下推,那么判断where条件是否匹配会提前。若不匹配则提前调用函数row_unlock_for_mysql释放聚集索引上的锁

6)另外一个优化:返回mysql层后,判断where不匹配,则会调用unlock_row函数释放锁。注:这里update在innodb层没有发生锁冲突,成功加上了锁。即没有半一致性读

猜你喜欢

转载自blog.51cto.com/yanzongshuai/2106100