handle

    技术2022-07-01  96

    函数所在文件:mysqld.cc

    该函数用于处理客户端的请求,当一个请求到达时,需要为该请求分配或新建一个线程

    运行一个while循环来接受请求:

    while (!abort_loop) //当需要退出时置1 在循环体内使用select函数来对请求进行监听: select((int) max_used_connection,&readFDs,0,0,0) 设置服务器socket为非阻塞模式: fcntl(sock, F_SETFL, flags | O_NONBLOCK);

    再使用标准库函数accept接受请求:

    new_sock = accept(sock, my_reinterpret_cast(struct sockaddr *) (&cAddr),&length);

    当完成select()/accecpt()等操作后,分配一个THD实例:

    if (!(thd= new THD)) { (void) shutdown(new_sock, SHUT_RDWR); VOID(closesocket(new_sock)); continue; }

    打开连接,读取fcntl状态,并初始化任务线程描述符的网络操作:

    if (!(vio_tmp=vio_new(new_sock, sock == unix_sock ? VIO_TYPE_SOCKET : VIO_TYPE_TCPIP, sock == unix_sock ? VIO_LOCALHOST: 0)) || my_net_init(&thd->net,vio_tmp))

     

    最后,调用函数创建一个新的线程:

    create_new_thread(thd);

     

    在上述函数中,有两种可能分配线程:

    1.使用缓存中的线程来分配

    2.创建一个新的线程

    具体实现取决于配置文件,无论何种情况,都会为这个新的请求赋予一个线程id

    thd->thread_id= thd->variables.pseudo_thread_id= thread_id++; thread_count++; thread_scheduler.add_connection(thd); 全局变量thread_scheduler用于管理线程的建立,在一个连接一个线程的情况下,将调用函数: void create_thread_to_handle_connection(THD *thd) 当一个停用线程缓存或线程缓存中暂无可用线程时,将要创建一个新的线程,相关代码如下: if (cached_thread_count > wake_thread) { /* Get thread from cache */ thread_cache.append(thd); wake_thread++; pthread_cond_signal(&COND_thread_cache); } else { char error_message_buff[MYSQL_ERRMSG_SIZE]; /* Create new thread to handle connection */ int error; thread_created++; threads.append(thd); DBUG_PRINT("info",(("creating thread %lu"), thd->thread_id)); thd->connect_utime= thd->start_utime= my_micro_time(); if ((error=pthread_create(&thd->real_id,&connection_attrib, handle_one_connection, (void*) thd))) ……

    新分配的线程从文件handle_one_connection()开始执行后续的一系列操作.

     

     


    最新回复(0)