偷偷摘套内射激情视频,久久精品99国产国产精,中文字幕无线乱码人妻,中文在线中文a,性爽19p

MariaDB線程池源碼分析

數(shù)據(jù)庫 MySQL MariaDB
MySQL5.5的Enterprise版本以plugin的方式引入了thread pool,在并發(fā)請求數(shù)達到一定 數(shù)量的時候,性能相比社區(qū)版貌似有不少提高, 可以看下這個性能對比。

 在引入線程池之前,MySQL支持的線程處理方式(thread_handling參數(shù)控制)有no-threads和one-thread-per-connection兩種方式,no-threads方式是指任一時刻最多只有一個連接可以連接到server,一般用于實驗性質(zhì)。 one-thread-per-connection是指針對每個連接創(chuàng)建一個線程來處理這個連接的所有請求,直到連接斷開,線程 結(jié)束。是thread_handling的默認方式。

one-thread-per-connection存在的問題就是需要為每個連接創(chuàng)建一個新的thread,當并發(fā)連接數(shù)達到一定 程度,性能會有明顯下降,因為過多的線程會導(dǎo)致頻繁的上下文切換,CPU cache命中率降低和鎖的競爭 更加激烈。

解決one-thread-per-connection的方法就是降低線程數(shù),這樣就需要多個連接共用線程,這便引入了線程 池的概念。線程池中的線程是針對請求的,而不是針對連接的,也就是說幾個連接可能使用相同的線程處理 各自的請求。

MariaDB在5.5引入了一個動態(tài)的線程池方案,可以根據(jù)當前請求的并發(fā)情況自動增加或減少線程數(shù),還好 MariaDB完全開源,本文結(jié)合MariaDB的代碼來介紹下thread pool的實現(xiàn)。這里使用的MariaDB 10.0的 代碼樹。

1  相關(guān)參數(shù)

MySQL的參數(shù)都寫在sys_vars.cc文件下。

  1. static Sys_var_uint Sys_threadpool_idle_thread_timeout( 
  2.   "thread_pool_idle_timeout"
  3.   "Timeout in seconds for an idle thread in the thread pool." 
  4.   "Worker thread will be shut down after timeout"
  5.   GLOBAL_VAR(threadpool_idle_timeout), CMD_LINE(REQUIRED_ARG), 
  6.   VALID_RANGE(1, UINT_MAX), DEFAULT(60), BLOCK_SIZE(1) 
  7. ); 
  8. static Sys_var_uint Sys_threadpool_oversubscribe( 
  9.   "thread_pool_oversubscribe"
  10.   "How many additional active worker threads in a group are allowed."
  11.   GLOBAL_VAR(threadpool_oversubscribe), CMD_LINE(REQUIRED_ARG), 
  12.   VALID_RANGE(1, 1000), DEFAULT(3), BLOCK_SIZE(1) 
  13. ); 
  14. static Sys_var_uint Sys_threadpool_size( 
  15.  "thread_pool_size"
  16.  "Number of thread groups in the pool. " 
  17.  "This parameter is roughly equivalent to maximum number of concurrently " 
  18.  "executing threads (threads in a waiting state do not count as executing)."
  19.   GLOBAL_VAR(threadpool_size), CMD_LINE(REQUIRED_ARG), 
  20.   VALID_RANGE(1, MAX_THREAD_GROUPS), DEFAULT(my_getncpus()), BLOCK_SIZE(1), 
  21.   NO_MUTEX_GUARD, NOT_IN_BINLOG, ON_CHECK(0), 
  22.   ON_UPDATE(fix_threadpool_size) 
  23. ); 
  24. static Sys_var_uint Sys_threadpool_stall_limit( 
  25.  "thread_pool_stall_limit"
  26.  "Maximum query execution time in milliseconds," 
  27.  "before an executing non-yielding thread is considered stalled." 
  28.  "If a worker thread is stalled, additional worker thread " 
  29.  "may be created to handle remaining clients."
  30.   GLOBAL_VAR(threadpool_stall_limit), CMD_LINE(REQUIRED_ARG), 
  31.   VALID_RANGE(10, UINT_MAX), DEFAULT(500), BLOCK_SIZE(1), 
  32.   NO_MUTEX_GUARD, NOT_IN_BINLOG, ON_CHECK(0),  
  33.   ON_UPDATE(fix_threadpool_stall_limit) 
  34. ); 

這幾個參數(shù)都有相應(yīng)的描述,這里再稍微具體介紹一下。

thread_pool_size: 線程池的分組(group)個數(shù)。MariaDB的線程池并不是說一整個 大池子,而是分成了不同的group,而且是按照到來connection的順序進行分組的,如 第一個connection分配到group[0],那么第二個connection就分配到group[1],是一種 Round Robin的輪詢分配方式。默認值是CPU core個數(shù)。

thread_pool_idle_timeout: 線程最大空閑時間,如果某個線程空閑的時間大于這個 參數(shù),則線程退出。

thread_pool_stall_limit: 監(jiān)控間隔時間,thread pool有個監(jiān)控線程,每隔這個時間, 會檢查每個group的線程可用數(shù)等狀態(tài),然后進行相應(yīng)的處理,如wake up或者create thread。

thread_pool_oversubscribe: 允許的每個group上的活躍的線程數(shù),注意這并不是每個group上的 最大線程數(shù),而只是可以處理請求的線程數(shù)。

2  thread handling設(shè)置

thread pool模式其實是新增了一種thread_handling的方式,即在配置文件中設(shè)置:

  1. [mysqld] 
  2. thread_handling=pool-of-threads. 
  3. .... 

 MySQL內(nèi)部是有一個scheduler_functions結(jié)構(gòu)體,不論thread_handling是哪種方式,都是通過設(shè)置這個 結(jié)構(gòu)體中的函數(shù)來進行不同的調(diào)度。

  1. /** scheduler_functions結(jié)構(gòu)體 */ 
  2. struct scheduler_functions 
  3.   uint max_threads, *connection_count; 
  4.   ulong *max_connections; 
  5.   bool (*init)(void); 
  6.   bool (*init_new_connection_thread)(void); 
  7.   void (*add_connection)(THD *thd); 
  8.   void (*thd_wait_begin)(THD *thd, int wait_type); 
  9.   void (*thd_wait_end)(THD *thd); 
  10.   void (*post_kill_notification)(THD *thd); 
  11.   bool (*end_thread)(THD *thd, bool cache_thread); 
  12.   void (*end)(void); 
  13. }; 
  14. static int get_options(int *argc_ptr, char ***argv_ptr) 
  15.   ... 
  16.   /** 根據(jù)thread_handling選項的設(shè)置,選擇不同的處理方式*/ 
  17. if (thread_handling <= SCHEDULER_ONE_THREAD_PER_CONNECTION) 
  18.     /**one thread per connection 方式 */ 
  19.     one_thread_per_connection_scheduler(thread_scheduler, &max_connections, 
  20.                                         &connection_count); 
  21.   else if (thread_handling == SCHEDULER_NO_THREADS) 
  22.     /** no thread 方式 */ 
  23.     one_thread_scheduler(thread_scheduler); 
  24.   else 
  25.     /** thread pool 方式 */ 
  26.     pool_of_threads_scheduler(thread_scheduler,  &max_connections, 
  27.                                         &connection_count);  
  28.   ...                                         
  29. static scheduler_functions tp_scheduler_functions
  30.   0,                                  // max_threads 
  31.   NULL, 
  32.   NULL, 
  33.   tp_init,                            // init 
  34.   NULL,                               // init_new_connection_thread 
  35.   tp_add_connection,                  // add_connection 
  36.   tp_wait_begin,                      // thd_wait_begin 
  37.   tp_wait_end,                        // thd_wait_end 
  38.   post_kill_notification,             // post_kill_notification 
  39.   NULL,                               // end_thread 
  40.   tp_end                              // end 
  41. }; 
  42. void pool_of_threads_scheduler(struct scheduler_functions *func, 
  43.     ulong *arg_max_connections, 
  44.     uint *arg_connection_count) 
  45.   /** 設(shè)置scheduler_functions結(jié)構(gòu)體為tp_scheduler_functions */ 
  46.   *func = tp_scheduler_functions
  47.   func->max_threadsthreadpool_max_threads
  48.   func->max_connectionsarg_max_connections
  49.   func->connection_countarg_connection_count
  50.   scheduler_init(); 

上面可以看到設(shè)置了thread_scheduler的處理函數(shù)為tp_scheduler_functions,即 為thread pool方式,這種方式對應(yīng)的初始函數(shù)為tp_init, 創(chuàng)建新連接的函數(shù)為 tp_add_connection,等待開始函數(shù)為tp_wait_begin,等待結(jié)束函數(shù)為tp_wait_end. 這里說明下等待函數(shù)的意義,等待函數(shù)一般是在等待磁盤I/O,等待鎖資源,SLEEP,或者等待 網(wǎng)絡(luò)消息的時候,調(diào)用wait_begin,在等待結(jié)束后調(diào)用wait_end,那么為什么要等待的時候 調(diào)用等待函數(shù)呢?這個在后面進行介紹。

上面講的其實和thread pool關(guān)系不是很大,下面開始thread pool流程的介紹。thread pool涉及 到的源碼在emphsql/threadpool_common.cc和emphsql/threadpool_unix.cc, 對于windows而言,還有emphsql/threadpool_win.cc.

3  線程池初始化——tp_init

  1. >tp_init 
  2. >thread_group_init 
  3. >start_timer 

tp_init非常簡單,首先是調(diào)用了thread_group_init進行組的初始化, 然后調(diào)用的start_timer開啟了監(jiān)控線程timer_thread。 至此為止,thread pool里面只有一個監(jiān)控線程啟動,而沒有任何工作線程, 直到有新的連接到來。

4  添加新連接——tp_add_connection

  1. void tp_add_connection(THD *thd) 
  2.   DBUG_ENTER("tp_add_connection"); 
  3.   threads.append(thd); 
  4.   mysql_mutex_unlock(&LOCK_thread_count); 
  5.   connection_t *connectionalloc_connection(thd); 
  6.   if (connection) 
  7.   { 
  8.     thd->event_scheduler.dataconnection
  9.     /* Assign connection to a group. */ 
  10.     thread_group_t *group=  
  11.       &all_groups[thd->thread_id%group_count]; 
  12.     connection->thread_group=group; 
  13.     mysql_mutex_lock(&group->mutex); 
  14.     group->connection_count++; 
  15.     mysql_mutex_unlock(&group->mutex); 
  16.     /* 
  17.        Add connection to the work queue.Actual logon  
  18.        will be done by a worker thread. 
  19.     */ 
  20.    queue_put(group, connection); 
  21.   } 
  22.   else 
  23.   { 
  24.     /* Allocation failed */ 
  25.     threadpool_remove_connection(thd); 
  26.   }  
  27.   DBUG_VOID_RETURN; 

但server的主監(jiān)聽線程監(jiān)聽到有客戶端的connect時,會調(diào)用tp_add_connection函數(shù)進行處理。 首先根據(jù)thread_id對group_count取模,找到其所屬的group,然后調(diào)用queue_put將此connection 放入到group中的queue中。這里涉及到兩個新的結(jié)構(gòu)體,connection_t和thread_group_t。

  1. struct connection_t 
  2.   THD *thd; 
  3.   thread_group_t *thread_group; 
  4.   connection_t *next_in_queue; 
  5.   connection_t **prev_in_queue; 
  6.   ulonglong abs_wait_timeout; //等待超時時間 
  7.   bool logged_in; //是否進行了登錄驗證 
  8.   bool bound_to_poll_descriptor; //是否添加到了epoll進行監(jiān)聽 
  9.   bool waiting; //是否在等待狀態(tài),如I/O, sleep 
  10. }; 
  11. struct thread_group_t  
  12.   mysql_mutex_t mutex; 
  13.   connection_queue_t queue;  //connection請求鏈表 
  14.   worker_list_t waiting_threads; //group中正在等待被喚醒的thread 
  15.   worker_thread_t *listener;  //當前group中用于監(jiān)聽的線程 
  16.   pthread_attr_t *pthread_attr; 
  17.   int  pollfd;  //epoll 文件描述符,用于綁定group中的所有連接 
  18.   int  thread_count;  //線程數(shù) 
  19.   int  active_thread_count;//活躍線程數(shù) 
  20.   int  connection_count; //連接數(shù) 
  21.   /* Stats for the deadlock detection timer routine.*/ 
  22.   int io_event_count;  //epoll產(chǎn)生的事件數(shù) 
  23.   int queue_event_count; //工作線程消化的事件數(shù) 
  24.   ulonglong last_thread_creation_time; 
  25.   int  shutdown_pipe[2]; 
  26.   bool shutdown; 
  27.   bool stalled; // 工作線程是否處于停滯狀態(tài) 
  28. } MY_ALIGNED(512); 

上面對這些參數(shù)進行了說明,理解這些參數(shù)的意義,才能了解這個動態(tài)thread pool的管理機制, 因為每個參數(shù)都會影響到thread pool的增長或收縮。

介紹完結(jié)構(gòu)體,繼續(xù)回到新的連接到來,這時會調(diào)用queue_put函數(shù),將此connection放到 group的隊列queue中。

  1. static void queue_put(thread_group_t *thread_group, connection_t *connection) 
  2.   DBUG_ENTER("queue_put"); 
  3.   mysql_mutex_lock(&thread_group->mutex); 
  4.   thread_group->queue.push_back(connection); 
  5.   if (thread_group->active_thread_count == 0) 
  6.     wake_or_create_thread(thread_group); 
  7.   mysql_mutex_unlock(&thread_group->mutex); 
  8.   DBUG_VOID_RETURN; 

注意,這時候有個active_thread_count的判斷,如果沒有活躍的線程,那么就無法處理 這個新到的請求啊,這時就需要調(diào)用wake_or_create_thread,這個函數(shù)首先會嘗試喚醒group 等待線程鏈表waiting_threads中的線程,如果沒有等待中的線程,則需要創(chuàng)建一個線程。 至此,新到的connection被掛到了group的queue上,這樣一個連接算是add進隊列了,那么如何 處理這個連接呢?我們繼續(xù)往下看。

5  工作線程——worker_main

由于是第一個連接到來,那么肯定沒有waiting_threads,此時會調(diào)用create_worker 函數(shù)創(chuàng)建一個工作線程。我們直接來看下工作線程。

  1. static void *worker_main(void *param) 
  2.  ... 
  3.   DBUG_ENTER("worker_main"); 
  4.   thread_group_t *thread_group = (thread_group_t *)param; 
  5.   /* Run event loop */ 
  6.   for(;;) 
  7.   { 
  8.     connection_t *connection; 
  9.     struct timespec ts; 
  10.     set_timespec(ts,threadpool_idle_timeout); 
  11.     connection = get_event(&this_thread, thread_group, &ts); 
  12.     if (!connection) 
  13.       break; 
  14.     this_thread.event_count++; 
  15.     handle_event(connection); 
  16.   } 
  17.   .... 
  18.   my_thread_end(); 
  19.   return NULL; 

上面是整個工作線程的邏輯,可以看到是一個循環(huán),get_event用來獲取新的需要處理的 connection,然后調(diào)用handle_event進行處理相應(yīng)的connection。one thread per connection 中每個線程也是一個循環(huán)體,這兩者之間的區(qū)別就是,thread pool的循環(huán)等待的是一個可用的event, 并不局限于某個固定的connection的event,而one thread per connection的循環(huán)等待是等待固定的 connection上的event,這就是兩者最大的區(qū)別。

6  事件獲取——get_event

工作線程通過get_event獲取需要處理的connection,

  1. connection_t *get_event(worker_thread_t *current_thread,  
  2.   thread_group_t *thread_group,  struct timespec *abstime) 
  3. {  
  4.   ... 
  5.   for(;;)  
  6.   { 
  7.   ... 
  8.       /** 從QUEUE中獲取connection */ 
  9.       connection = queue_get(thread_group); 
  10.       if(connection) { 
  11.         fprintf(stderr, "Thread %x get a new connection.\n", (unsigned int)pthread_self()); 
  12.         break; 
  13.       } 
  14.      ... 
  15.       /**監(jiān)聽epoll */ 
  16.     if(!thread_group->listener) 
  17.     { 
  18.       thread_group->listenercurrent_thread
  19.       thread_group->active_thread_count--; 
  20.       mysql_mutex_unlock(&thread_group->mutex); 
  21.       fprintf(stderr, "Thread %x waiting for a new event.\n", (unsigned int)pthread_self()); 
  22.       connection = listener(current_thread, thread_group); 
  23.       fprintf(stderr, "Thread %x get a new event for connection %p.\n", 
  24.               (unsigned int)pthread_self(), connection); 
  25.       mysql_mutex_lock(&thread_group->mutex); 
  26.       thread_group->active_thread_count++; 
  27.       /* There is no listener anymore, it just returned. */ 
  28.       thread_group->listenerNULL
  29.       break; 
  30.     } 
  31.     ... 

這個get_event的函數(shù)邏輯稍微有點多,這里只抽取了獲取事件的兩個點, 我們接著按照第一個連接到來是的情形進行說明, 第一個連接到來,queue中有了一個connection,這是get_event便會從queue中獲取到一個 connection,返回給worker_main線程。worker_main接著調(diào)用handle_event進行事件處理。

每個新的connection連接到服務(wù)器后,其socket會綁定到group的epoll中,所以,如果queue中 沒有connection,需要從epool中獲取,每個group的所有連接的socket都綁定在group的epool 中,所以任何一個時刻,最多只有一個線程能夠監(jiān)聽epoll,如果epoll監(jiān)聽到有event的話,也會返回 相應(yīng)的connection,然后再調(diào)用handle_event進行處理。

7  事件處理——handle_event

handle_event的邏輯比較簡單,就是根據(jù)connection_t上是否登錄過,進行分支,如果沒 登錄過,說明是新到的連接,則進行驗證,否則直接進行請求處理。

  1. static void handle_event(connection_t *connection) 
  2.   DBUG_ENTER("handle_event"); 
  3.   int err; 
  4.   if (!connection->logged_in) //處理登錄 
  5.   { 
  6.     errthreadpool_add_connection(connection->thd); 
  7.     connection->logged_intrue
  8.   } 
  9.   else  //處理請求 
  10.   { 
  11.     errthreadpool_process_request(connection->thd); 
  12.   } 
  13.   if(err) 
  14.     goto end; 
  15.   set_wait_timeout(connection); 
  16.   /** 設(shè)置socket到epoll的監(jiān)聽 */ 
  17.   errstart_io(connection); 
  18. end: 
  19.   if (err) 
  20.     connection_abort(connection); 
  21.   DBUG_VOID_RETURN; 
  22. static int start_io(connection_t *connection) 
  23. {  
  24.   int fd = mysql_socket_getfd(connection->thd->net.vio->mysql_socket); 
  25.   ... 
  26.   /* 綁定到epoll *。 
  27.   if (!connection->bound_to_poll_descriptor) 
  28.   { 
  29.     connection->bound_to_poll_descriptortrue
  30.     return io_poll_associate_fd(group->pollfd, fd, connection); 
  31.   } 
  32.   return io_poll_start_read(group->pollfd, fd, connection); 

注意,在handle_event之后,會調(diào)用start_io,這個函數(shù)很重要,這個函數(shù)會將新 到的connection的socket綁定到group的epoll上進行監(jiān)聽。

8  線程等待

當group中的線程沒有任務(wù)執(zhí)行時,所有線程都會在get_event處等待,但是有兩種等待方式, 一種是在epoll上等待事件,每個group中只有一個線程會做這個事情,且這個會一直等待,直到有新 的事件到來。另一種就是等待一定的時間, 即參數(shù)thread_pool_idle_time這個時間,如果超過了這個時間,那么當前的線程的get_event就會 返回空,然后worker_main線程就會退出。如果在線程等待的過程被喚醒的話,那么就會繼續(xù)在 get_event中進行循環(huán),等待新的事件。

9  喚醒等待線程

有兩種方式會喚醒等待的線程,一種是監(jiān)控線程timer_thread,另一種就是一些active的線程碰到 需要等待的時候,會調(diào)用tp_wait_begin,這個函數(shù)如果判斷當前沒有active的thread且沒有thread監(jiān)聽 epoll,則會調(diào)用wake_or_create_thread。

監(jiān)控線程timer_thread用于定期監(jiān)控group中的thread使用情況,具體的檢查函數(shù)是check_stall.

  1. void check_stall(thread_group_t *thread_group) 
  2.   ... 
  3.   /** 如果沒有線程監(jiān)聽epoll且自上次檢查到現(xiàn)在沒有新的event事件產(chǎn)生,說明所有的 
  4.   活躍線程都在 忙于執(zhí)行長任務(wù),則需要喚醒或創(chuàng)建工作線程 */ 
  5.   if (!thread_group->listener && !thread_group->io_event_count) 
  6.   { 
  7.     wake_or_create_thread(thread_group); 
  8.     mysql_mutex_unlock(&thread_group->mutex); 
  9.     return; 
  10.   } 
  11.   /*  Reset io event count */ 
  12.   thread_group->io_event_count0
  13.   /** 如果隊列queue中有請求,且自上次檢查到現(xiàn)在queue中的請求沒有被消化, 
  14.   則說明所有活躍線程忙于執(zhí)行長任務(wù),需要喚醒或創(chuàng)建工作線程*/ 
  15.   if (!thread_group->queue.is_empty() && !thread_group->queue_event_count) 
  16.   { 
  17.     thread_group->stalledtrue
  18.     wake_or_create_thread(thread_group); 
  19.   } 
  20.   /* Reset queue event count */ 
  21.   thread_group->queue_event_count0
  22.   mysql_mutex_unlock(&thread_group->mutex); 

10  小結(jié)

MariaDB的thread pool的實現(xiàn)相對比較簡單,總體上就是將group中所有的connection的socket掛在 group的epoll_fd上進行事件監(jiān)聽,監(jiān)聽到的事件或被當前線程執(zhí)行,或者被push到group的queue上 被其他線程執(zhí)行。

監(jiān)控線程timer_thread定期的根據(jù)需要去喚醒等待線程或創(chuàng)建新的線程,來達到動態(tài)增加的thread的 目的。而thread的收縮則是通過線程等待事件超時來完成的。

btw,在跟蹤代碼的過程中,也發(fā)現(xiàn)了使用thread pool時導(dǎo)致server crash的情況,提交了個 bug給MariaDB,發(fā)現(xiàn)當天就有回復(fù), 并立刻修復(fù)push到source tree上了,看來MariaDB的團隊反映夠迅速的,贊一個。

原文鏈接:http://www.cnblogs.com/nocode/archive/2013/05/25/3098317.html

責任編輯:彭凡 來源: 博客園
相關(guān)推薦

2018-10-31 15:54:47

Java線程池源碼

2011-08-16 09:34:34

Nginx

2022-12-16 08:31:37

調(diào)度線程池源碼

2017-02-08 13:03:40

Java線程池框架

2022-11-09 09:01:08

并發(fā)編程線程池

2013-06-08 10:11:31

Java線程池架構(gòu)

2015-10-10 09:39:42

Java線程池源碼解析

2023-12-28 07:49:11

線程池源碼應(yīng)用場景

2021-05-26 11:30:24

Java線程池代碼

2024-01-29 15:54:41

Java線程池公平鎖

2023-05-19 08:01:24

Key消費場景

2024-02-04 08:43:20

源碼線程池緩沖

2025-04-16 08:50:00

信號量隔離線程池隔離并發(fā)控制

2024-07-15 08:20:24

2023-10-13 08:20:02

Spring線程池id

2012-05-15 02:18:31

Java線程池

2020-12-10 08:24:40

線程池線程方法

2017-03-31 21:15:36

進程線程池Binde

2025-06-23 00:00:02

線程池Java任務(wù)隊列

2023-06-07 13:49:00

多線程編程C#
點贊
收藏

51CTO技術(shù)棧公眾號