[转帖]MySQL一个线程处理一个连接源码_MySQL, Oracle及数据库讨论区_Weblogic技术|Tuxedo技术|中间件技术|Oracle论坛|JAVA论坛|Linux/Unix技术|hadoop论坛_联动北方技术论坛  
网站首页 | 关于我们 | 服务中心 | 经验交流 | 公司荣誉 | 成功案例 | 合作伙伴 | 联系我们 |
联动北方-国内领先的云技术服务提供商
»  游客             当前位置:  论坛首页 »  自由讨论区 »  MySQL, Oracle及数据库讨论区 »
总帖数
1
每页帖数
101/1页1
返回列表
0
发起投票  发起投票 发新帖子
查看: 1479 | 回复: 0   主题: [转帖]MySQL一个线程处理一个连接源码        下一篇 
ad222888
注册用户
等级:新兵
经验:66
发帖:134
精华:0
注册:2016-9-25
状态:离线
发送短消息息给ad222888 加好友    发送短消息息给ad222888 发消息
发表于: IP:您无权察看 2018-8-28 15:54:14 | [全部帖] [楼主帖] 楼主

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




赞(0)    操作        顶端 
总帖数
1
每页帖数
101/1页1
返回列表
发新帖子
请输入验证码: 点击刷新验证码
您需要登录后才可以回帖 登录 | 注册
技术讨论