原理解析
1. MySQL的默认处理方式
MySQL默认的线程处理方式是:one-thread-per-connection (服务器使用一个线程处理每个客户端连接),意思就是我们一个连接connection对应一个线程, 然后可以设置最大的connection连接数,max_connections。
这里有一个问题是,当我们的线程运行比较多的时候,由于资源的占用以及线程调度的消耗,往往mysql的性能会下降,而正常环境不可避免会有会有很多的连接,所以我们就需要用到mysql的线程池对线程数量进行限制。
2.线程池整体原理图

本图隐藏了一些实现细节,主要包括以下几个点:
1. MySQL **conn_handler** 模块用于管理连接,有一个**Connection_hander**的接口(虚基类),线程池(Thread_pool_connection_handler)实现了该接口。
2. Thread_pool_connection_handler 主要实现了四个过程:1. 现成池初始化`tp_init()`,图中用**绿色**表示;2. 连接建立于处理,图中**蓝色**的部分;3. 进程退出线程池结束部分,图中**红色**部分;4. Timer 线程定期检查过程
3. 线程池主要的数据结构与过程,数据结构包括 **thread_group_t**、**connection_t**、**pool_timer_t**、**worker_thread_t**。**worker_main**为工作线程处理函数,**timer_thread**为定时器线程
3.MySQL Conn_hander 模块
MySQL与连接和线程管理相关的代码主要在sql/conn_handler中,主要包括以下类:
- Connection_handler_manager:单例类,用来管理连接处理器;
- Connection_handler:连接处理的抽象类,具体实现由其子类实现;
- Per_thread_connection_handler:继承了Connection_handler,每一个连接用单独的线程处理,默认为该实现,通过thread_handling参数可以设置;
- One_thread_connection_handler:继承了Connection_handler,所有连接用同一个线程处理;
- Plugin_connection_handler:继承了Connection_handler,支持由Plugin具体实现的handler,例如线程池(官方);
- Connection_acceptor:一个模版类,以模版方式支持不同的监听实现(三个listener)。并且提供一个死循环,用以监听连接;
- Shared_mem_listener:通过共享内存的监听方式;
- Named_pipe_listener:通过命名管道来监听和接收客户请求;
- Channel_info:连接信道的抽象类,具体实现有Channel_info_local_socket和Channel_info_tcpip_socket,
- Channel_info_local_socket:与本地方式与服务器进行交互;
- Channel_info_tcpip_socket:以TCP/IP方式与服务器进行交互;
- TCP_socket:TCP socket,与MySQL服务不同机器的连接访问;
- Unix_socket:Unix socket,与MySQL服务相同主机的连接访问;
MySQL接收到连接并accept后,将进入`Connection_handler_manager::process_new_connection`,对应代码如下,最终是调用了`Connection_handler::add_connection`方法。在线程池模式下,实际就是调用`Thread_pool_connection_handler::add_connection`方法。
void Connection_handler_manager::process_new_connection(
Channel_info *channel_info) {
if (connection_events_loop_aborted() ||
!check_and_incr_conn_count(channel_info->is_admin_connection())) {
channel_info->send_error_and_close_channel(ER_CON_COUNT_ERROR, 0, true);
delete channel_info;
return;
}
if (m_connection_handler->add_connection(channel_info)) {
inc_aborted_connects();
delete channel_info;
}
}
注意的是,本线程池的实现没用实现成插件的形式,而是在内核代码里添加相应功能。
4.线程池的主要数据结构
thread_group_t
struct thread_group_t
{
mysql_mutex_t mutex; --锁变量,保证每次操作不被影响
connection_queue_t queue; --事件队列
connection_queue_t high_prio_queue; --高优先级的事件队列
worker_list_t waiting_threads; --等待线程队列,线程每次执行完后会进入睡眠状态等待下次唤醒工作
worker_thread_t *listener; --监听线程,负责监听命令事件,事件队列为空时也会充当工作线程
pthread_attr_t *pthread_attr; --线程属性
int pollfd; --poll文件描述符
int thread_count; --线程数
int active_thread_count; --活跃线程数
int connection_count; --连接数
int waiting_thread_count; --等待线程数
/* Stats for the deadlock detection timer routine.*/
int io_event_count; --io事件数
int queue_event_count; --事件队列的数量
ulonglong last_thread_creation_time;--高优先级的事件队列的数量
int shutdown_pipe[2]; --管道通信
bool shutdown; --判断关闭的变量
bool stalled; --判断停滞的变量
}
- 每一个 thread_group_t 对应一组线程,包括一个listener线程与多个worker线程。一般来说一个thread_group最理想的情况是同一时间只有一个“激活”线程。
- queue 与 high_prio_queue 是事件的队列,每个事件实际是一个 connection_t,即一个连接。queue的选择根据全局变量threadpool_high_prio_mode和每个连接的ticket决定。
- waiting_threads,等待线程队列,线程每次执行完后会进入睡眠状态等待下次唤醒工作,将自己加入到 waiting_threads 队列头部,等待有事件过来唤醒,此队列是FILO,主要为了能重用最近的缓存。
- listener,监听线程,负责监听命令事件,事件队列为空时也会充当工作线程。这样做主要为了减少线程的唤醒,可以直接使用被唤醒的listen线程处理相关工作。如改线程阻塞,则通过timer的 check stall 机制增加线程。最坏情况可能退化为one_thread_per_connection
- 如原理图,全局有一个thread_group_t数组,大小是`MAX_THREAD_GROUPS=128`。线程池初始化时将初始化其中`threadpool_size`个group,threadpool_size 要 <=MAX_THREAD_GROUPS。图中紫色为初始化了的thread_group。
connection_t
struct connection_t
{
THD *thd; --连接对应的thd
thread_group_t *thread_group; --指向所在的thread_group
connection_t *next_in_queue; --用于connection_queue_t,指向下一connection_t
connection_t **prev_in_queue; --用于connection_queue_t
ulonglong abs_wait_timeout; --连接超时时间
bool logged_in; --连接登录成功标志
bool bound_to_poll_descriptor; --是否绑定到了thread_group的pollfd
bool waiting; --是否等待中
uint tickets; --threadpool_high_prio_mode为TP_HIGH_PRIO_MODE_TRANSACTIONS下,本链接事件进入高优先
--级队列的“票数”
};
worker_thread_t
struct worker_thread_t
{
ulonglong event_count; /* number of request handled by this thread */(暂时没实际作用)
thread_group_t* thread_group; --指向所在线程组(暂时没实际作用)
worker_thread_t *next_in_list; --用于waiting thread队列
worker_thread_t **prev_in_list; --用于waiting thread队列
mysql_cond_t cond; --用于唤醒线程的信号量
bool woken; --是否被唤醒
};
pool_timer_t
struct pool_timer_t
{
mysql_mutex_t mutex;
mysql_cond_t cond;
volatile uint64 current_microtime; --当前时间,微妙
volatile uint64 next_timeout_check; --下一个启动检查时间
int tick_interval; --最小时间间隔
bool shutdown; --是否关闭
};
5. 线程池初始化过程
从进程启动开始,设置线程池模式后,整个初始化调用链为:
-mysqld.cc mysqld_main()
-mysqld.cc init_common_variables()
-mysqld.cc get_options()
-connection_handler_manager.cc Connection_handler_manager init()
-connection_handler_impl.h Thread_pool_connection_handler()
-threadpool_uinx.cc tp_init()
如原理图,在tp_init()中主要完成了:
1. 初始化all_group,先将所有group的fd和shutdown_pipe设成-1,然后真正初始化all_group的`threadpool_size`个`thread_group_t`元素,并创建group内的pollfd
2. start_timer,启动定时线程。
6. 处理连接加入以及命令的接收
这部分为线程池的核心逻辑,在原理图中由蓝色部分的流程简要描述。一个连接上来后,内核代码调用链为:
-mysqld.cc mysqld_main()
-connection_acceptor.h connection_event_loop()
-connection_handler_manager.cc process_new_connection()
-threadpool_unix.cc Thread_pool_connection_handler::add_connection(Channel_info *channel_info)
在`Thread_pool_connection_handler::add_connection(Channel_info *channel_info)`方法中,处理新链接,大致流程如原理图:
1. 创建新的 thd
2. 创建 connection,并将 connection 赋值到`thd->event_scheduler.data`中
3. thd 添加到 thd_manager
4. 根据`thd->thread_id % threadpool_size`选择要处理的 thread_group
5. connection 加入到选中的 thread_group 的 queue队列中等待被取出处理
6. 唤醒或创建一个线程:1. 当waiting_threads 队列有元素时,取出线程并唤醒;2. 当 waiting_threads 为空,判断是否满足可新建线程条件后,新建线程处理 connection 队列事件。
7. 切换到被唤醒或新建的线程上后,进入工作循环,首先阻塞地调用 get_event() 获取事件,get_event() 的逻辑后续再详细讨论。若get_event 返回错误则退出循环,最终退出线程
8. 获取 event 后 handle_event 处理事件
9. 第一次处理事件时,调用 threadpool_add_connection() 添加链接,设置`logged_in=true`,重新进入 get_event() 等待事件
10. 第二次时间处理时,调用 threadpool_process_request() 处理链接请求
9、10步后会重新设置连接的超时时间,并再次等待 get_event() 返回。整个worker_main主体的流程如下,可以看出是个比较简单的流程控制:
static void *worker_main(void *param)
{
...
for(;;)
{
connection_t *connection;
struct timespec ts;
set_timespec(&ts, threadpool_idle_timeout);
connection = get_event(&this_thread, thread_group, &ts);
if (!connection)
break;
this_thread.event_count++;
handle_event(connection);
}
...
}
static void handle_event(connection_t *connection)
{
...
if (!connection->logged_in)
{
err= threadpool_add_connection(connection->thd);
connection->logged_in= true;
}
else
{
err= threadpool_process_request(connection->thd);
}
if(err)
goto end;
set_wait_timeout(connection);
err= start_io(connection);
end:
if (err)
connection_abort(connection);
DBUG_VOID_RETURN;
}
上述过程是主体的流程,忽略了一些细节:
- thread_group 具有两个connection队列,一个是高优先级队列 high_prio_queue,事件进入那个队列主要由环境变量**threadpool_high_prio_mode**以及连接状态决定:
// threadpool_high_prio_mode 变量取值范围
enum tp_high_prio_mode_t {
TP_HIGH_PRIO_MODE_TRANSACTIONS, // 事务的前tickets个命令,并且拥有锁时进入高优先级
TP_HIGH_PRIO_MODE_STATEMENTS, // 用户命令均进入高优先级
TP_HIGH_PRIO_MODE_NONE // 无高优先级
};
inline bool connection_is_high_prio(const connection_t *c)
{
const ulong mode= c->thd->variables.threadpool_high_prio_mode;
return (mode == TP_HIGH_PRIO_MODE_STATEMENTS) ||
(mode == TP_HIGH_PRIO_MODE_TRANSACTIONS && c->tickets > 0 &&
(thd_is_transaction_active(c->thd) ||
c->thd->variables.option_bits & OPTION_TABLE_LOCK ||
c->thd->locked_tables_mode != LTM_NONE ||
c->thd->mdl_context.has_locks() ||
c->thd->global_read_lock.is_acquired() ||
// c->thd->backup_tables_lock.is_acquired() ||
// c->thd->backup_binlog_lock.is_acquired() ||
c->thd->mdl_context.has_locks(MDL_key::USER_LEVEL_LOCK) ||
c->thd->mdl_context.has_locks(MDL_key::LOCKING_SERVICE)));
}
- threadpool_add_connection() 里会调用`thd_prepare_connection(THD *thd)`进行连接的登录、thd初始化等工作。
- get_event() 中有很多实现的细节:
1. get_event() 会通过长轮询等待事件(记住get_event是在worker里执行的),长轮询最开始会判断是否有过多"活跃"线程,当判断超过配置的threadpool_oversubscribe数量并且本group没有stall住时,此线程不处理任何东西直接丢进waiting_threads队列。这个是为了控制并发的量的机制。
2. 进行事件listen的线程是会继续处理获取到的事件的,这取决于事件队列中是否还有其它事件,这样做的目的为了减少线程切换的开销。这样做有可能导致 group 没有线程进行 listen 导致 stall。这个交由 timer 进行检查并恢复
流程图如下:

- handle_event() 在获取事件后, handle_event()进行新增连接或者处理主流程代码如下。`threadpoll_add_connection()`将线程登录,之后`Threadpool_prcoess_request()`通过`do_command()`进入mysql命令解析与处理流程。
static void handle_event(connection_t *connection)
{
...
int err;
if (!connection->logged_in)
{
err= threadpool_add_connection(connection->thd);
connection->logged_in= true;
}
else
{
err= threadpool_process_request(connection->thd);
}
...
}
7. 定时检查过程
定时检查的过程比较简单,如原理图橙色部分所示,每次定时器到时后,做两件事情:
1. 检查每个group有没有stall
2. 从thd_manager取出并检查每个connection是否超时
static void* timer_thread(void *param)
{
...
for(;;)
{
...
if (err == ETIMEDOUT)
{
timer->current_microtime= my_microsecond_getsystime();
/* Check stalls in thread groups */
for(i=0; i< array_elements(all_groups);i++)
{
if(all_groups[i].connection_count)
check_stall(&all_groups[i]);
}
/* Check if any client exceeded wait_timeout */
if (timer->next_timeout_check <= timer->current_microtime)
timeout_check(timer);
}
...
}
...
}
8. 线程池退出
线程池退出过程调用tp_end(),停止定时器,对thread_group进行资源'transactions', 'statements' or 'none'回收,最终会等待所有worker线程退出才返回。