MySQL新增一个连接源码


当客户端向服务器发起查询时,就是和服务器之间建立了一个连接。而MySQL是提供了一个最大连接数限制的。所以,每次在一个连接建立成功后,服务器要给该连接分配处理线程的时候会判断现在的连接数是否已经操作了配置的最大连接数了。如果已经超过,则不会再分配线程来处理,直接关闭在连接。

static void create_new_thread(THD *thd)
{
DBUG_ENTER("create_new_thread");
/*
Don't allow too many connections. We roughly check here that we allow
only (max_connections + 1) connections.
*/
mysql_mutex_lock(&LOCK_connection_count);
if (connection_count >= max_connections + 1 || abort_loop)
{//判断是否超过最大连接或是否标志终止,该最大连接是在my.ini文件中配置的,
mysql_mutex_unlock(&LOCK_connection_count);
DBUG_PRINT("error",("Too many connections"));
close_connection(thd, ER_CON_COUNT_ERROR);
delete thd;
DBUG_VOID_RETURN;
}
++connection_count;//如果没有,增加连接数
if (connection_count > max_used_connections)
max_used_connections= connection_count;//增加最大使用连接数
mysql_mutex_unlock(&LOCK_connection_count);
/* Start a new thread to handle connection. */
mysql_mutex_lock(&LOCK_thread_count);
/*
The initialization of thread_id is done in create_embedded_thd() for
the embedded library.
TODO: refactor this to avoid code duplication there
*/
thd->thread_id= thd->variables.pseudo_thread_id= thread_id++;
thread_count++;//增加线程数,准备为该连接分配线程了(见面的函数)
MYSQL_CALLBACK(thread_scheduler, add_connection, (thd));
DBUG_VOID_RETURN;
}

相关内容