linux線程池的實現

     什麼時候需要創建線程池呢?簡單的說,如果一個應用需要頻繁的創建和銷燬線程,而任務執行的時間又非常短,這樣線程創建和銷燬的帶來的開銷就不容忽視,這 時也是線程池該出場的機會了。如果線程創建和銷燬時間相比任務執行時間可以忽略不計,則沒有必要使用線程池了。

   下面是Linux系統下用C語言創建的一個線程池。線程池會維護一個任務鏈表(每個CThread_worker結構就是一個任務)。
   pool_init()函數預先創建好max_thread_num個線程,每個線程執thread_routine ()函數。該函數中

  1. while (pool->cur_queue_size == 0)
  2. {
  3.        pthread_cond_wait (&(pool->queue_ready),&(pool->queue_lock));
  4. }
表示如果任務鏈表中沒有任務,則該線程出於阻塞等待狀態。否則從隊列中取出任務並執行。
  
   pool_add_worker()函數向線程池的任務鏈表中加入一個任務,加入後通過調用pthread_cond_signal (&(pool->queue_ready))喚醒一個出於阻塞狀態的線程(如果有的話)。
  
   pool_destroy ()函數用於銷燬線程池,線程池任務鏈表中的任務不會再被執行,但是正在運行的線程會一直把任務運行完後再退出。

下面貼出完整代碼
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <unistd.h>
  4. #include <sys/types.h>
  5. #include <pthread.h>
  6. #include <assert.h>

  7. /*
  8. *線程池裏所有運行和等待的任務都是一個CThread_worker
  9. *由於所有任務都在鏈表裏,所以是一個鏈表結構
  10. */
  11. typedef struct worker
  12. {
  13.     /*回調函數,任務運行時會調用此函數,注意也可聲明成其它形式*/
  14.     void *(*process) (void *arg);
  15.     void *arg;/*回調函數的參數*/
  16.     struct worker *next;

  17. } CThread_worker;


  18. /*線程池結構*/
  19. typedef struct
  20. {
  21.      pthread_mutex_t queue_lock;
  22.      pthread_cond_t queue_ready;

  23.     /*鏈表結構,線程池中所有等待任務*/
  24.      CThread_worker *queue_head;

  25.     /*是否銷燬線程池*/
  26.     int shutdown;
  27.      pthread_t *threadid;
  28.     /*線程池中允許的活動線程數目*/
  29.     int max_thread_num;
  30.     /*當前等待隊列的任務數目*/
  31.     int cur_queue_size;

  32. } CThread_pool;


  33. int pool_add_worker (void *(*process) (void *arg), void *arg);
  34. void *thread_routine (void *arg);


  35. static CThread_pool *pool = NULL;
  36. void
  37. pool_init (int max_thread_num)
  38. {
  39.      pool = (CThread_pool *) malloc (sizeof (CThread_pool));

  40.      pthread_mutex_init (&(pool->queue_lock), NULL);
  41.      pthread_cond_init (&(pool->queue_ready), NULL);

  42.      pool->queue_head = NULL;

  43.      pool->max_thread_num = max_thread_num;
  44.      pool->cur_queue_size = 0;

  45.      pool->shutdown = 0;

  46.      pool->threadid =
  47.          (pthread_t *) malloc (max_thread_num * sizeof (pthread_t));
  48.     int i = 0;
  49.     for (i = 0; i < max_thread_num; i++)
  50.      {
  51.          pthread_create (&(pool->threadid[i]), NULL, thread_routine,
  52.                  NULL);
  53.      }
  54. }


  55. /*向線程池中加入任務*/
  56. int
  57. pool_add_worker (void *(*process) (void *arg), void *arg)
  58. {
  59.     /*構造一個新任務*/
  60.      CThread_worker *newworker =
  61.          (CThread_worker *) malloc (sizeof (CThread_worker));
  62.      newworker->process = process;
  63.      newworker->arg = arg;
  64.      newworker->next = NULL;/*別忘置空*/

  65.      pthread_mutex_lock (&(pool->queue_lock));
  66.     /*將任務加入到等待隊列中*/
  67.      CThread_worker *member = pool->queue_head;
  68.     if (member != NULL)
  69.      {
  70.         while (member->next != NULL)
  71.              member = member->next;
  72.          member->next = newworker;
  73.      }
  74.     else
  75.      {
  76.          pool->queue_head = newworker;
  77.      }

  78.      assert (pool->queue_head != NULL);

  79.      pool->cur_queue_size++;
  80.      pthread_mutex_unlock (&(pool->queue_lock));
  81.     /*好了,等待隊列中有任務了,喚醒一個等待線程;
  82.      注意如果所有線程都在忙碌,這句沒有任何作用*/
  83.      pthread_cond_signal (&(pool->queue_ready));
  84.     return 0;
  85. }


  86. /*銷燬線程池,等待隊列中的任務不會再被執行,但是正在運行的線程會一直
  87. 把任務運行完後再退出*/
  88. int
  89. pool_destroy ()
  90. {
  91.     if (pool->shutdown)
  92.         return -1;/*防止兩次調用*/
  93.      pool->shutdown = 1;

  94.     /*喚醒所有等待線程,線程池要銷燬了*/
  95.      pthread_cond_broadcast (&(pool->queue_ready));

  96.     /*阻塞等待線程退出,否則就成殭屍了*/
  97.     int i;
  98.     for (i = 0; i < pool->max_thread_num; i++)
  99.          pthread_join (pool->threadid[i], NULL);
  100.      free (pool->threadid);

  101.     /*銷燬等待隊列*/
  102.      CThread_worker *head = NULL;
  103.     while (pool->queue_head != NULL)
  104.      {
  105.          head = pool->queue_head;
  106.          pool->queue_head = pool->queue_head->next;
  107.          free (head);
  108.      }
  109.     /*條件變量和互斥量也別忘了銷燬*/
  110.      pthread_mutex_destroy(&(pool->queue_lock));
  111.      pthread_cond_destroy(&(pool->queue_ready));
  112.     
  113.      free (pool);
  114.     /*銷燬後指針置空是個好習慣*/
  115.      pool=NULL;
  116.     return 0;
  117. }


  118. void *
  119. thread_routine (void *arg)
  120. {
  121.      printf ("starting thread 0x%x\n", pthread_self ());
  122.     while (1)
  123.      {
  124.          pthread_mutex_lock (&(pool->queue_lock));
  125.         /*如果等待隊列爲0並且不銷燬線程池,則處於阻塞狀態; 注意
  126.          pthread_cond_wait是一個原子操作,等待前會解鎖,喚醒後會加鎖*/
  127.         while (pool->cur_queue_size == 0 && !pool->shutdown)
  128.          {
  129.              printf ("thread 0x%x is waiting\n", pthread_self ());
  130.              pthread_cond_wait (&(pool->queue_ready), &(pool->queue_lock));
  131.          }

  132.         /*線程池要銷燬了*/
  133.         if (pool->shutdown)
  134.          {
  135.             /*遇到break,continue,return等跳轉語句,千萬不要忘記先解鎖*/
  136.              pthread_mutex_unlock (&(pool->queue_lock));
  137.              printf ("thread 0x%x will exit\n", pthread_self ());
  138.              pthread_exit (NULL);
  139.          }

  140.          printf ("thread 0x%x is starting to work\n", pthread_self ());

  141.         /*assert是調試的好幫手*/
  142.          assert (pool->cur_queue_size != 0);
  143.          assert (pool->queue_head != NULL);
  144.         
  145.         /*等待隊列長度減去1,並取出鏈表中的頭元素*/
  146.          pool->cur_queue_size--;
  147.          CThread_worker *worker = pool->queue_head;
  148.          pool->queue_head = worker->next;
  149.          pthread_mutex_unlock (&(pool->queue_lock));

  150.         /*調用回調函數,執行任務*/
  151.          (*(worker->process)) (worker->arg);
  152.          free (worker);
  153.          worker = NULL;
  154.      }
  155.     /*這一句應該是不可達的*/
  156.      pthread_exit (NULL);
  157. }

    下面是測試代碼
  1. void *
  2. myprocess (void *arg)
  3. {
  4.      printf ("threadid is 0x%x, working on task %d\n", pthread_self (),*(int *) arg);
  5.      sleep (1);/*休息一秒,延長任務的執行時間*/
  6.     return NULL;
  7. }

  8. int
  9. main (int argc, char **argv)
  10. {
  11.      pool_init (3);/*線程池中最多三個活動線程*/
  12.     
  13.     /*連續向池中投入10個任務*/
  14.     int *workingnum = (int *) malloc (sizeof (int) * 10);
  15.     int i;
  16.     for (i = 0; i < 10; i++)
  17.      {
  18.          workingnum[i] = i;
  19.          pool_add_worker (myprocess, &workingnum[i]);
  20.      }
  21.     /*等待所有任務完成*/
  22.      sleep (5);
  23.     /*銷燬線程池*/
  24.      pool_destroy ();

  25.      free (workingnum);
  26.     return 0;
  27. }
將上述所有代碼放入threadpool.c文件中,
在Linux輸入編譯命令
$ gcc -o threadpool threadpool.c -lpthread

以下是運行結果
starting thread 0xb7df6b90
thread 0xb7df6b90 is waiting
starting thread 0xb75f5b90
thread 0xb75f5b90 is waiting
starting thread 0xb6df4b90
thread 0xb6df4b90 is waiting
thread 0xb7df6b90 is starting to work
threadid is 0xb7df6b90, working on task 0
thread 0xb75f5b90 is starting to work
threadid is 0xb75f5b90, working on task 1
thread 0xb6df4b90 is starting to work
threadid is 0xb6df4b90, working on task 2
thread 0xb7df6b90 is starting to work
threadid is 0xb7df6b90, working on task 3
thread 0xb75f5b90 is starting to work
threadid is 0xb75f5b90, working on task 4
thread 0xb6df4b90 is starting to work
threadid is 0xb6df4b90, working on task 5
thread 0xb7df6b90 is starting to work
threadid is 0xb7df6b90, working on task 6
thread 0xb75f5b90 is starting to work
threadid is 0xb75f5b90, working on task 7
thread 0xb6df4b90 is starting to work
threadid is 0xb6df4b90, working on task 8
thread 0xb7df6b90 is starting to work
threadid is 0xb7df6b90, working on task 9
thread 0xb75f5b90 is waiting
thread 0xb6df4b90 is waiting
thread 0xb7df6b90 is waiting
thread 0xb75f5b90 will exit
thread 0xb6df4b90 will exit
thread 0xb7df6b90 will exit
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章