---
title: "改进MySQL的table_cache"
author: "sogotobj"
date: "2011-11-02T19:28:00Z"
tags: []
slug: "mysql-table-cache"
draft: false
lastmod: "2011-11-09T19:56:47Z"
id: 1247669
url: "https://sogotobj.iteye.com/blog/1247669"
---

以下为本人在工作中的碎碎念，记录的比较凌乱……

........................................................................

在mysql里面有一个参数table\_cache，当设置过大时，会产生明显的效率下降。这是因为扫描open\_cache哈希表时，使用的线性扫描，时间复杂度为O(n)，mysql的bug list上有人提供了一个patch（[http://bugs.mysql.com/bug.php?id=33948](http://bugs.mysql.com/bug.php?id=33948)），可以把时间降到o(1)，其基本思想是为table实例增加三个指针，来维护一个空闲链表。

首先，我们分析一下mysql在打开一个表时如何工作：

在mysql里，table\_cache是一个比较重要的参数。由于多线程机制，每个线程独自打开自己需要的标的文件描述符，而不是共享已经打开的。

1\. table\_cache key （见create\_table\_def\_key）

在内存里，table cache使用hash表来存储，key为 database\_name\\0table\_name\\0+（可选的，用于临时表）

这里对于临时表会做特殊处理，需要增加额外的信息来保证临时表在slave端是唯一的

增加8个字节：前4个字节为master thread id，后4个字节为slavb

2.打开表时候的处理：open\_table

\*\*\*\*\*\*\*\*\*\*\*\*\*\**

必要的检查：线程栈是否足够，thd是否被kill

\*\*\*\*\*\*\*\*\*\*\*\*\**

全局锁：lock\_open

\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\**

首先判断是否是临时表

\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\**

这里有一段很有意思的逻辑，当需要打开表时，总是先从临时表链表中查找表。也就是说，当存在一个与实际表同名的临时表时，会总是操作临时表

if (!table\_list-&gt;skip\_temporary)  
{  
for (table= thd-&gt;temporary\_tables; table ; table=table-&gt;next)  
{

\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\**

非临时表，且处于pre-locked 或 lock\_tables mode（thd-&gt;locked\_tables || thd-&gt;prelocked\_mode）

即该线程已经打开或锁定了一些表，从thd-&gt;open\_tables里查询，当不存在时，返回error

\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\**

if (thd-&gt;locked\_tables || thd-&gt;prelocked\_mode)  
{ // Using table locks  
TABLE \*best\_table= 0;  
int best\_distance= INT\_MIN;  
for (table=thd-&gt;open\_tables; table ; table=table-&gt;next)  
{

\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\**

正常情况：

1\. 首先尝试从table cache中取table

2\. 当找到的TABLE实例是nam-locked的，或者一些线程正在flush tables，我们需要等待，直到锁释放

3\. 如果不存在这样的TABLE，我们需要创建TABLE，并将其加入到cache中

！这些操作都需要全局锁：LOCK\_open,来保护table cache和磁盘上的表定义

\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\**

如果这是该query打开的第一个表：设置thd-&gt;version = refresh\_version，这样，当我们打开剩余表的过程中，如果 version发生了变化，则需要back off，关闭所有已经打开的并重新打开表

目前refresh\_version只会被FLUSH TABLES命令改变

if (thd-&gt;handler\_tables)  
mysql\_ha\_flush(thd); //刷新（关闭并标记为re-open）所有需要reopen的表

查询table cache的过程：

for (table= (TABLE\*) hash\_first(&open\_cache, (uchar\*) key, key\_length, //基于同一个key来查找hash表  
&state);  
table && table-&gt;in\_use ;  
table= (TABLE\*) hash\_next(&open\_cache, (uchar\*) key, key\_length,  
&state))

{

\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\**

flush tables marked for flush.

Normally, table-&gt;s-&gt;version contains the value of  
refresh\_version from the moment when this table was  
(re-)opened and added to the cache.  
If since then we did (or just started) FLUSH TABLES  
statement, refresh\_version has been increased.  
For "name-locked" TABLE instances, table-&gt;s-&gt;version is set  
to 0 (see lock\_table\_name for details).  
In case there is a pending FLUSH TABLES or a name lock, we  
need to back off and re-start opening tables.  
If we do not back off now, we may dead lock in case of lock  
order mismatch with some other thread:  
c1: name lock t1; -- sort of exclusive lock  
c2: open t2; -- sort of shared lock  
c1: name lock t2; -- blocks  
c2: open t1; -- blocks

\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\**

if (table-&gt;needs\_reopen\_or\_name\_lock()) //Is this instance of the table should be reopen or represents a name-lock?

{}

}

if (table)

\*\*\*\*\*\*\*\*\*\*\**

从unused\_tables链表中移除刚找到的table

\*\*\*\*\*\*\*\*\*\*\**

else

\*\*\*\*\*\*\*\*\*\**

创建一个新的table实例，并插入到open cache中

\*\*\*\*\*\*\*\*\*\**

while (open\_cache.records &gt; table\_cache\_size && unused\_tables) //当cache满时，从中释放未使用的TABLE实例

hash\_delete(&open\_cache,(uchar\*) unused\_tables);

if (table\_list-&gt;create) //创建一个新表

{

\*\*\*\*\*\**

检查表是否存在：check\_if\_table\_exists

\*\*\*\*\*\**

在table cache的hash中创建一个placeholder(占位符)：table\_cache\_insert\_placeholder

将占位符链到open tables list上：

table-&gt;open\_placeholder= 1;  
table-&gt;next= thd-&gt;open\_tables;  
thd-&gt;open\_tables= table;

return table

}

创建一个新的table实例

分配内存table=(TABLE\*) my\_malloc(sizeof(\*table),MYF(MY\_WME))

error= open\_unireg\_entry(thd, table, table\_list, alias, key, key\_length,  
mem\_root, (flags & OPEN\_VIEW\_NO\_PARSE));

如果是视图 or error &lt; 0 释放内存，返回;

my\_hash\_insert(&open\_cache,(uchar\*) table)

\------------------------------------------------

patch:http://bugs.mysql.com/bug.php?id=33948

增加3个指针：

hash\_head:

hash\_prev: always point to unused table cached items

hash\_next: always point to used table cached items

修改的函数：

free\_cache\_entry //释放一个表的内存。

close\_thread\_table //move one table to free list

reopen\_name\_locked\_table //重新打开表，保持链表结构

table\_cache\_insert\_placeholder

open\_table

\------------------------------------------------------------------------

总结：

增加了三个指针:

hash\_head:

hash\_prev:

hash\_next:

!.............................!head!.........................!

head的左边为空闲item链表

head的右边为占用的item链表

所有item通过hash\_prev和hash\_next进行双向指针

右边的item的hash\_head指向head

操作链表：

1)插入新空闲item：在head节点前加入

2)插入新的被占用item:在head后面加入

3)从链表中删除item:

---若该item为head，修改head右侧的item的hash\_head指向head-&gt;next

---否则，直接删除item，并释放内存。。

查询空闲节点：

1\) 找到head

2\) 检测head是否in\_use，为False则table = head, true则找到table = head-&gt;prev

3)当table 不为NULL时，表示找到一个item，将其插入到head右侧

3\) table依旧为NULL----&gt;创建新item，将其插入到head右侧

\------------------------------

转载请注明：印风