MySQL一個線程處理一個串連源碼

來源:互聯網
上載者:User

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"));//線程建立成功
}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.