MySQL 支援執行緒快取:連線斷開時,若快取未滿,將執行緒放入閒置池供下次複用;啟動參數 --thread_cache_size=10 控制池大小。
static bool cache_thread() {
safe_mutex_assert_owner(&LOCK_thread_count);
if (cached_thread_count < thread_cache_size && !abort_loop && !kill_cached_threads) {
cached_thread_count++;
while (!abort_loop && !wake_thread && !kill_cached_threads)
(void) pthread_cond_wait(&COND_thread_cache, &LOCK_thread_count);
cached_thread_count--;
if (kill_cached_threads)
pthread_cond_signal(&COND_flush_thread_cache);
if (wake_thread) {
THD *thd = thread_cache.get();
thd->thread_stack = (char*)&thd;
(void) thd->store_globals();
thd->mysys_var->abort = 0;
thd->thr_create_utime = my_micro_time();
threads.append(thd);
return true; // 成功從快取取得執行緒
}
}
return false; // 快取已滿或關閉,需建立新執行緒
}
thread_cache_size:啟動參數設定的上限cached_thread_count:目前快取中的閒置執行緒數wake_thread:等待被喚醒的執行緒計數kill_cached_threads:關閉快取的旗標Windows 平台下透過 WaitForMultipleObjects 實作條件變數等待,支援無限等待(INFINITE)與超時機制。關鍵流程:
WaitForSingleObject 等待廣播封鎖事件WaitForMultipleObjects(2, events, FALSE, timeout)void create_thread_to_handle_connection(THD *thd) {
if (cached_thread_count > wake_thread) {
thread_cache.append(thd);
wake_thread++;
pthread_cond_signal(&COND_thread_cache); // 喚醒一個閒置執行緒
} else {
// 建立新執行緒...
}
}
Threads_created:累積建立執行緒數,若持續快速增長,說明 thread_cache_size 過小Threads_cached:目前快取中的執行緒數thread_cache_size 設為 Max_connections 的 10%-20%,或觀察 Threads_created 穩定後調整執行緒快取透過「生產者-消費者」模式,以條件變數協調閒置執行緒的回收與喚醒,避免頻繁建立/銷毀執行緒的系統開銷。原始碼展現了 MySQL 在跨平台執行緒同步上的精細實作。