After a new MySQL connection arrives, a thread is allocated to the thread. If the server has Idle threads cached, use them directly. If no available cache thread exists, re-create a thread for this connection.
/*
Schedconnection that uses one thread per connection
*/
Void create_thread_to_handle_connection (THD * thd)
{
If (cached_thread_count> wake_thread) // a cache thread exists during determination.
{
/* Get thread from cache */
Thread_cache.append (thd); // If a cache thread exists, the connection information is sent to the thread for processing.
Wake_thread ++;
Mysql_cond_signal (& COND_thread_cache); // activate the cached thread to start processing connection information
}
Else // enter Else, indicating there is no available cache thread
{
Char error_message_buff [MYSQL_ERRMSG_SIZE];
/* Create new thread to handle connection */
Int error;
Thread_created ++; // create a new thread. The number of threads is + 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) // create a thread
{
/* Purecov: begin inspected */
DBUG_PRINT ("error ",
("Can't create thread to handle request (error % d )",
Error ));
Thread_count --; // If creation fails,-1 is performed.
Thd-> killed = THD: KILL_CONNECTION; // Safety
Mysql_mutex_unlock (& LOCK_thread_count );
Mysql_mutex_lock (& LOCK_connection_count );
-- Connection_count; // indicates that the connection is not processed by the thread.
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), // write the Error Log
ER_THD (thd, ER_CANT_CREATE_THREAD), error );
Net_send_error (thd, ER_CANT_CREATE_THREAD, error_message_buff, NULL); // error message sent to the client
Close_connection (thd); // end the connection
Mysql_mutex_lock (& LOCK_thread_count );
Delete thd; // delete resources not allocated by the connection
Mysql_mutex_unlock (& LOCK_thread_count );
Return;
/* Purecov: end */
}
}
Mysql_mutex_unlock (& LOCK_thread_count );
DBUG_PRINT ("info", ("Thread created"); // The Thread is created successfully.
}