mysql alter table的过程

今天遇到一个有趣的问题,即多个update操作与alter操作如何来竞争锁的问题,猜想mysql内部可能会使用一个队列来控制,但具体是什么样的队列,还不清楚。

简单的跟踪了下,一个alter操作其实可以切分成多个过程:


1. 创建一个临时表,例如(table_name=0x48fa7720 "#sql-2f8e_3")

2.为临时表创建索引

3.index_read

4.index_write 将原表的索引数据写入新索引

5.将原表数据写入临时表

6.将原表进行rename,例如:

ha_innobase::rename_table (this=<value optimized out>, from=0x48fa5d10 "./zhaiwx/test", to=0x48fa5b00 "./zhaiwx/#sql2-2f8e-3")

7.将临时表rename为原表,例如:

ha_innobase::rename_table (this=<value optimized out>, from=0x48fa5d10 "./zhaiwx/#sql-2f8e_3", to=0x48fa5b00 "./zhaiwx/test")

8.删除原表:

ha_innobase::delete_table (this=<value optimized out>, name=0x48fa5de0 "./zhaiwx/#sql2-2f8e-3") at handler/ha_innodb.cc:6622

--------------------------------------------

以上是跟踪gdb的副产物,真实性有待证实,跟踪的方法是在lock_table函数设断点,每次bt,可以很清晰明了的看到alter的过程。。。

在一次alter table操作过程中,多次调用了lock_table函数。那么进入该函数,我们可以发现,其做了以下工作:

1.

/* Look for stronger locks the same trx already has on the table */ if (lock_table_has(trx, table, mode)) { lock_mutex_exit_kernel(); return(DB_SUCCESS); }

2.

/* We have to check if the new lock is compatible with any locks other transactions have in the table lock queue. */ if (lock_table_other_has_incompatible(trx, LOCK_WAIT, table, mode)) { /* Another trx has a request on the table in an incompatible mode: this trx may have to wait */ err = lock_table_enqueue_waiting(mode | flags, table, thr); lock_mutex_exit_kernel(); return(err); } lock_table_create(table, mode | flags, trx);

-----------------

跟进到lock_table_other_has_incomatible函数,可以发现,会对一个锁队列进行遍历,判断其中是否有和当前要求的锁相冲突的,如果有,那么就需要

调用lock_table_enqueue_waiting函数将当前请求加入到锁队列中,并等待(除此外,还会检查是否可能产生死锁,具体尚未分析)。


可见,mysql是用锁队列(lock queue)来控制可能产生冲突的请求,锁的类型包括:

/* Basic lock modes */ enum lock_mode { LOCK_IS = 0, /* intention shared */ LOCK_IX, /* intention exclusive */ LOCK_S, /* shared */ LOCK_X, /* exclusive */ LOCK_AUTO_INC, /* locks the auto-inc counter of a table in an exclusive mode */ LOCK_NONE, /* this is used elsewhere to note consistent read */ LOCK_NUM = LOCK_NONE/* number of lock modes */ };
---------------------------------

mysql锁的管理还是相当复杂的,本文只是找到了一个研究锁管理的入口,至于其内部具体如何管理的,还需要更加深入的研究


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值