MySQL新到來一個串連後,會為該線程分配一個線程。如果伺服器已經有閒置線程被緩衝了,則直接使用。如果沒有緩衝可用的線程,則重新建立一個線程給該串連使用。
/*
Scheduler that uses one thread per connection
*/
void create_thread_to_handle_connection(THD *thd)
{
if (cached_thread_count > wake_thread)//判斷時候有緩衝線程
{
/* Get thread from cache */
thread_cache.append(thd);//如果有緩衝線程,則將該串連資訊交給該線程處理
wake_thread++;
mysql_cond_signal(&COND_thread_cache);//啟用被緩衝的線程開始處理串連資訊
}
Else//進入Else,表示沒有可用的緩衝線程了
{
char error_message_buff[MYSQL_ERRMSG_SIZE];
/* Create new thread to handle connection */
int error;
thread_created++;//建立新線程,線程數+1,
threads.append(thd);
DBUG_PRINT("info",(("creating thread %lu"), thd->thread_id));
thd->prior_thr_create_utime= thd->start_utime= my_micro_time();
if ((error= mysql_thread_create(key_thread_one_connection,
&thd->real_id, &connection_attrib,
handle_one_connection,
(void*) thd)))//建立線程
{
/* purecov: begin inspected */
DBUG_PRINT("error",
("Can't create thread to handle request (error %d)",
error));
thread_count--;//建立失敗,則執行-1操作
thd->killed= THD::KILL_CONNECTION; // Safety
mysql_mutex_unlock(&LOCK_thread_count);
mysql_mutex_lock(&LOCK_connection_count);
--connection_count;//到此,表示該串連沒有被線程處理
mysql_mutex_unlock(&LOCK_connection_count);
statistic_increment(aborted_connects,&LOCK_status);
/* Can't use my_error() since store_globals has not been called. */
my_snprintf(error_message_buff, sizeof(error_message_buff),//寫錯誤記錄檔
ER_THD(thd, ER_CANT_CREATE_THREAD), error);
net_send_error(thd, ER_CANT_CREATE_THREAD, error_message_buff, NULL);//向用戶端發生錯誤資訊
close_connection(thd);//結束該串連
mysql_mutex_lock(&LOCK_thread_count);
delete thd;//刪除未該串連分配的資源
mysql_mutex_unlock(&LOCK_thread_count);
return;
/* purecov: end */
}
}
mysql_mutex_unlock(&LOCK_thread_count);
DBUG_PRINT("info",("Thread created"));//線程建立成功
}