MySQL multi-threaded server implementation(mysql 5.1.49)
Main topic主线程loop监听连接请求,开启线程处理客户query请求客户处理线程处理query请求,一个线程一次只能服务于一个client,一个线程可能服务多个client(thread pool 机制)
Sample of pstackpstack <pid_mysqld>
主线程处理流程主线程处理流程(mysqld.cc main函数)参数初始化 init_common_variables线程处理机制 get_options – 一个线程处理一个连接one_thread_per_connection_scheduler(&thread_scheduler)网络初始化network_init开启网络监听(tcp/ip socket)开启本地监听(unix domain socket或named pipe)handle_connections_sockets(0),进入主线程loop接受客户端连接请求(tcp/ip socket connect request)开启线程处理客户端query请求(dml,ddl,.etc)
handle_connections_socketshandle_connections_sockets  loop建立网络连接( socket accept)建立THD, 将thd和新建立的socket连接关联起来my_net_init(&thd->net,vio_tmp))开启线程服务客户 create_new_thread(thd)create_new_thread调用了thread_scheduler.add_connection(thd), thread_scheduler是一个全局变量,mysqld启动的时候被初始化 (one_thread_per_connection_scheduler(&thread_scheduler)
Thread_schedule结构thread_scheduler
构造函数
thread_scheduler初始化Schedule.ccCreate_thread_to_handle_connection从thread pool取出一个线程, 或新建一个线程 pthread_createOne_thread_per_connection_end当前客户退出后,将线程放入thread pool
新建线程(pthread_create)create_thread_to_handle_connection刚开始,thread pool是空的,调用pthread_create创建新的线程新线程处理函数:handle_one_connection线程初始化 setup_connection_thread_globals登录,用户信息验证 login_connection(thd)进入loop, 处理客户端的querydo_command(…)客户端退出后,断开网络连接,将线程放入thread pool断开网络连接 end_connection线程进入thread pool睡眠 thread_scheduler.end_thread(thd,1)
thread_scheduler.end_thread(thd,1)one_thread_per_connection_endcache_thread不返回,直到该线程被主线程唤醒(从thread pool取出线程)唤醒后立刻处理新客户的请求
handle_one_connection
线程唤醒create_thread_to_handle_connection如果thread pool里有sleep的线程,则唤醒一个线程处理客户请求,主线程继续监听
Passing thd主线程创建thd, 传递给其他线程新建线程时,通过pthread_create传递thd从线程池唤醒一个线程时主线程将thd放到链表.子线程从链表中取出thd, 存到thread local storage子线程从tls中取出thd传递的是指向THD的指针,thread共享地址空间
thd->store_globals
current_thread
主线程loophandle_connections_sockets新建线程或唤醒thread pool的一个线程后,主线程继续监听,等待新的客户while(!abort_loop) {         accept(…)  // 建立网络连接create_new_thread(thd); //线程处理}
Do_commandDispatch_command
Mysql multi-threaded server building blocksTcp/Ip socket, Unix domain socket, named pipesPosix thread(pthread_create)Condition variables, mutex lockspthread_cond_wait, pthread_cond_timedwaitpthread_cond_signalpthread_cond_broadcastThread local storagepthread_setspecificpthread_getspecific
referencehttp://x.saw-unix.com/mysqld_thread_init.jpghttp://forge.mysql.com/wiki/MySQL_Internals_Guided_TourUnix network programming(richardstevens)Advanced programming in the Unix environment (richardstevens)

Mysql multi threaded_server_introduction