InnoDB---序列化隔离级别的实现

版权声明:本文为博主原创文章,未经博主允许可随意转载。 https://blog.csdn.net/fly2nn/article/details/70239811

序列化的实现

    InnoDB对于序列化的实现方式,是通过两种方式实现的。

    第一种,当SELECT语句在一个显式的事务块内,如执行表11-9中的编号为1的情况,将施加LOCK_S锁,根据表11-6(记录锁事务锁相容表)可知,LOCK_S锁排斥写锁,所以序列化隔离级别下只允许并发地读取操作,并发写被禁止,因此实现了可序列化(参见1.2.2节)。相应代码如下:

ha_innobase::external_lock(...)

{...

    if (lock_type != F_UNLCK) {

        /* MySQL is setting a new table lock */

...

        if (trx->isolation_level == TRX_ISO_SERIALIZABLE  //序列化隔离级别

            && m_prebuilt->select_lock_type == LOCK_NONE

            && thd_test_options(thd, OPTION_NOT_AUTOCOMMIT | OPTION_BEGIN)) { //且在一个显式事务块内部

 

            /* To get serializable execution, we let InnoDB conceptually add 'LOCK IN SHARE MODE' to all SELECTs

            which otherwise would have been consistent reads. An exception is consistent reads in the AUTOCOMMIT=1 mode:

            we know that they are read-only transactions, and they can be serialized also if performed as consistent reads. */

            m_prebuilt->select_lock_type = LOCK_S;  //加读锁,即 'LOCK IN SHARE MODE'

            m_prebuilt->stored_select_lock_type = LOCK_S;

        }  //否则,不加锁(这一点也很重要)

...

    } else {

        TrxInInnoDB::end_stmt(trx);

        DEBUG_SYNC_C("ha_innobase_end_statement");

    }

...}

    第二种,当SELECT语句不在一个显式的事务块内,则通过获取最新快照(在事务开始的时候,),然后读取数据。此时,因基于快照的一致性读不需要加锁,所以其加锁情况对应到了表11-9中的编号2对应的情况。

 

11-9 序列化隔离级别加锁情况

隔离级别

编号

SQL语句

施加的锁

SERIALIZABLE

1

BEGIN; S0;

LOCK_S + LOCK_REC_NOT_GAP

2

S0;

没有锁

说明:

q  S0SELECT * FROM bluesea WHERE c1=2;   //使用主键索引做WHERE条件

    另外,对于FLUSH...WITH READ LOCK语句,序列化隔离级别下也需要加读锁LOCK_S,代码如下:

ha_innobase::store_lock(

...

        /* Check for FLUSH TABLES ... WITH READ LOCK */

        if (trx->isolation_level == TRX_ISO_SERIALIZABLE) {

                m_prebuilt->select_lock_type = LOCK_S;

                m_prebuilt->stored_select_lock_type = LOCK_S;

        } else {

                m_prebuilt->select_lock_type = LOCK_NONE;

                m_prebuilt->stored_select_lock_type = LOCK_NONE;

        }    

...

}                      

    与序列化相关的,还有innobase_query_caching_of_table_permitted()函数,序列化隔离级别不允许缓冲查询。

展开阅读全文

没有更多推荐了,返回首页