MySQL 支援線程緩存:連線斷開時,將線程放入空閒池(thread_cache_size),新連線優先從池取用,避免頻繁建立/銷毀線程開銷。啟動參數:mysqld --thread_cache_size=10。
cache_thread())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)
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) {
wake_thread--;
THD *thd = thread_cache.get();
thd->thread_stack = (char*)&thd;
thd->store_globals();
thd->mysys_var->abort = 0;
thd->thr_create_utime = my_micro_time();
threads.append(thd);
return true; // 成功復用
}
}
return false; // 緩存已滿或關閉中,線程真正退出
}
關鍵點:pthread_cond_wait 掛起線程等待喚醒;cached_thread_count 計數器控制池大小上限。
create_thread_to_handle_connection())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 {
// 緩存不足,創建新線程
...
}
}
pthread_cond_timedwait)底層映射至 WaitForMultipleObjects:
abstime)。BROADCAST(廣播喚醒)與 SINGLE(單一喚醒)。thread_cache_size 設為 Max_connections * 0.1 或根據 Threads_created 狀態變數調整(若持續增長則調大)。Threads_cached、Threads_connected、Threads_running 狀態變數。