mysqld 是 MySQL 服務端核心進程,所有工作圍繞其展開。源碼入口為 mysqld_main()(在 mysqld.cc),經初始化後進入連接處理主循環。
handle_connections_methods() 創建三類監聽線程:
static void handle_connections_methods() {
mysql_mutex_lock(&LOCK_thread_count);
mysql_cond_init(key_COND_handler_count, &COND_handler_count, NULL);
handler_count = 0;
// 命名管道(Windows)
handler_count++;
mysql_thread_create(key_thread_handle_con_namedpipes, &hThread,
&connection_attrib, handle_connections_namedpipes, 0);
// TCP/IP Socket(主流)
handler_count++;
mysql_thread_create(key_thread_handle_con_sockets, &hThread,
&connection_attrib, handle_connections_sockets_thread, 0);
// 共享內存(Windows)
handler_count++;
mysql_thread_create(key_thread_handle_con_sharedmem, &hThread,
&connection_attrib, handle_connections_shared_memory, 0);
while (handler_count > 0)
mysql_cond_wait(&COND_handler_count, &LOCK_thread_count);
mysql_mutex_unlock(&LOCK_thread_count);
}
嵌入式場景用管道/共享內存,常規網絡環境以 TCP/IP 為主。Socket 監聽線程調用 handle_connections_sockets(),內部用 select() 監聽端口。
客戶端連接到達時:
THD (Thread Handler Data) 對象 —— 整個會話的「交際花」,贯穿解析、優化、執行、返回全過程VIO (Virtual I/O) 結構體 —— 通信中轉站,封裝 Socket 讀寫、SSL、壓縮等細節create_thread_to_handle_connection() 分發給工作線程void create_thread_to_handle_connection(THD *thd) {
if (cached_thread_count > wake_thread) {
// 唤醒緩存線程
mysql_cond_signal(&COND_thread_cache);
} else {
// 創建新線程
mysql_thread_create(key_thread_one_connection, &thd->real_id,
&connection_attrib, handle_one_connection, (void*)thd);
}
}
MySQL 維護線程緩存池(thread_cache_size),斷開連接的線程不銷毀而是入池,減少創建銷毀開銷。連接線程分發後繼續 select() 等待新連接。
handle_one_connection()
→ do_handle_one_connection()
→ init_new_connection_thread()
→ init_new_connection_handler_thread()
→ do_command() // 迴圈處理命令
→ dispatch_command() // 分發 COM_QUERY 等命令
→ mysql_parse() // SQL 解析
→ mysql_execute_command() // 執行
《深入理解 MySQL》有詳細代碼跟蹤,此處列出關鍵調用鏈供參考。後續流程涉及權限檢查、查詢緩存、解析器、優化器、執行引擎、存儲引擎接口等核心模塊。