简单线程池类

来源:互联网 发布:刘胜军 知乎 编辑:程序博客网 时间:2024/06/07 06:18

简单练习了一下代码,简单实现了一下线程池类,增加对线程的理解和掌控。以后有时间再好好完善下,现在和大家分享下:

[cpp] view plaincopy在CODE上查看代码片派生到我的代码片
  1. #include <stdio.h>  
  2. #include <stdlib.h>  
  3. #include <unistd.h>  
  4. #include <time.h>  
  5. #include <string.h>  
  6. #include <math.h>  
  7. #include <sys/types.h>  
  8. #include <stdlib.h>  
  9. #include <sys/ipc.h>  
  10. #include <sys/shm.h>  
  11. #include <pthread.h>  
  12. #include <assert.h>  
  13. #include <vector>  
  14. #include<iostream>  
  15.   
  16. using namespace std;  
  17.   
  18. typedef struct worker  
  19. {  
  20.     void* (*process)(void* arg);  
  21.     void* arg;  
  22.     pthread_t threadid;  
  23.   
  24. } worker_thread;  
  25.   
  26.   
  27.   
  28. typedef vector<worker_thread>::iterator TASK_ITERTOR;  
  29.   
  30. class ThreadPool  
  31. {  
  32. public:  
  33.   ThreadPool(void);  
  34.   ~ThreadPool(void);  
  35.   
  36.   
  37.   static ThreadPool& Instance(){static ThreadPool single; return single;}  
  38.   
  39.   bool Init(int number);  
  40.   
  41.   bool add(void *(*process) (void *arg), void *arg);  
  42.   
  43.   bool clear();  
  44.   
  45.   bool GetTask(int index);  
  46.   
  47.   void *thread_run();  
  48.   ///方法成员  
  49. public:  
  50.     
  51.   ///数据成员  
  52. private:  
  53.   
  54.    pthread_mutex_t m_lock;     //线程锁  
  55.    pthread_cond_t  m_ready;   //条件变量  
  56.    vector<worker_thread> m_threadPool; //线程容器  
  57.    int isDestory;       //是否销毁  
  58.    int m_max_thread_num; //活动的最大现场数  
  59.   
  60.    int cur_thread_index; //当前现场的索引  
  61.   
  62.    pthread_t* threadid;  
  63.   
  64.    TASK_ITERTOR m_iter;  
  65. };  
  66.   
  67.   
  68.   
  69. static void *run(void *arg)  
  70. {  
  71.     ThreadPool* p = (ThreadPool*)arg;  
  72.   
  73.     p->thread_run();  
  74.   
  75. }  
  76.   
  77.   
  78. ThreadPool::ThreadPool(void)  
  79. {  
  80.    m_max_thread_num = 0;  
  81.    cur_thread_index = 0;  
  82.    isDestory = 0;  
  83. }  
  84.   
  85. ThreadPool::~ThreadPool()  
  86. {  
  87.   
  88. }  
  89.   
  90. bool ThreadPool::Init(int number)  
  91. {  
  92.   
  93.    m_max_thread_num = number;  
  94.   
  95.    pthread_mutex_init(&m_lock,NULL);  
  96.    pthread_cond_init(&m_ready,NULL);  
  97.   
  98.    cur_thread_index = 0;  
  99.   
  100.    threadid = new pthread_t[number];  
  101.    
  102.    for (int thread_loop = 0;thread_loop < number;thread_loop++)  
  103.    {  
  104.        //printf("initital,create thread no.=%0x\n",threadid[thread_loop]);  
  105.        pthread_create(&threadid[thread_loop],NULL,run,(void*)(this));  
  106.    }  
  107.   
  108.      
  109.    return true;  
  110.   
  111. }  
  112.   
  113. bool ThreadPool::GetTask(int index)  
  114. {     
  115.      m_iter  = m_threadPool.begin();  
  116.      for (int i = 0;i< index;i++)  
  117.      {  
  118.         m_iter++;  
  119.      }  
  120. }  
  121.   
  122. bool ThreadPool::add(void *(* process)(void * arg),void * arg)  
  123. {  
  124.    worker_thread work;  
  125.   
  126.    work.arg = arg;  
  127.    work.process = process;  
  128.   
  129.    pthread_mutex_lock(&m_lock);  
  130.   
  131.    m_threadPool.push_back(work);  
  132.   
  133.    //ThreadPool::Instance().GetHead(cur_thread_index);  
  134.    cur_thread_index++;  
  135.     
  136.    pthread_mutex_unlock(&m_lock);  
  137.   
  138.    pthread_cond_signal(&m_ready);  
  139.   
  140.    //printf("task size=%d\n",m_threadPool.size());  
  141.    return true;  
  142. }  
  143.   
  144.   
  145. bool ThreadPool::clear()  
  146. {  
  147.    if (isDestory)  
  148.    {  
  149.        return true;  
  150.    }  
  151.   
  152.    isDestory = 1;  
  153.   
  154.    pthread_cond_broadcast(&m_ready);  
  155.   
  156.    for (int i = 0; i < m_max_thread_num; i++)  
  157.          pthread_join (threadid[i], NULL);  
  158.       
  159.    delete []threadid;  
  160.   
  161.    pthread_mutex_destroy(&m_lock);  
  162.    pthread_cond_destroy(&m_ready);  
  163.   
  164.    m_threadPool.clear();  
  165. }  
  166.   
  167. void * ThreadPool::thread_run()  
  168. {  
  169.      
  170.    printf("%0x thread is startting\n",pthread_self());  
  171.   
  172.     
  173.    int li_loop = 0;  
  174.      
  175.    while(1)  
  176.    {  
  177.        pthread_mutex_lock(&m_lock);  
  178.        //int* cur_index = (int*)arg;  
  179.        //printf("cur_thread_index=%d\n",cur_thread_index);  
  180.        while(cur_thread_index== 0 && !isDestory)  
  181.        {  
  182.             printf ("thread %0x is waiting\n", pthread_self ());  
  183.             pthread_cond_wait(&m_ready, &m_lock);  
  184.        }  
  185.   
  186.         if (isDestory)  
  187.        {  
  188.             
  189.            pthread_mutex_unlock (&m_lock);  
  190.            printf ("thread %0x will exit\n", pthread_self ());  
  191.            pthread_exit (NULL);  
  192.        }  
  193.           
  194.   
  195.        printf ("thread %0x is starting to work\n", pthread_self ());  
  196.   
  197.         
  198.        cur_thread_index--;  
  199.   
  200.            
  201.          worker_thread* work =&(*m_iter);  
  202.   
  203.          if (work != NULL)  
  204.          {  
  205.              (*(work->process))(m_iter->arg);  
  206.   
  207.              m_iter++;  
  208.          }  
  209.   
  210.           
  211.   
  212.     /* for (;iter != m_threadPool.end();++iter) 
  213.      { 
  214.          worker_thread* work =&(*iter); 
  215.  
  216.          (*(work->process))(iter->arg); 
  217.  
  218.          li_loop++; 
  219.  
  220.          if (li_loop == m_max_thread_num) 
  221.          { 
  222.               li_loop = 0; 
  223.                
  224.          } 
  225.      } */  
  226.         
  227.            
  228.          pthread_mutex_unlock(&m_lock);  
  229.   
  230.            
  231.            
  232.   
  233.     }  
  234.   
  235.     
  236. }  
  237.   
  238. void * task_run (void *arg)  
  239. {      
  240.      int* task_no = (int*)(arg);  
  241.      printf (" task %d is on working that threadid is %0x,\n", *task_no,pthread_self ());  
  242.      sleep (2);/*休息一秒,延长任务的执行时间*/  
  243.     return NULL;  
  244. }  
  245.   
  246.   
  247. char *GetCurrentTime(char *azp_CurrentTime)  
  248. {  
  249.   time_t lt_now_time;  
  250.   struct tm *local_time;  
  251.   time(<_now_time);  
  252.   local_time=localtime(<_now_time);  
  253.   
  254.   sprintf(azp_CurrentTime,"%d-%02d-%02d %02d:%02d:%02d",local_time->tm_year+1900,  
  255.     local_time->tm_mon+1,local_time->tm_mday,local_time->tm_hour,local_time->tm_min,local_time->tm_sec);  
  256.   return(azp_CurrentTime);  
  257. }  
  258.   
  259.   
  260. int DateTimeCmp(char *azp_DateTime1,    /*时间1*/  
  261.                 char *azp_DateTime2,    /*时间2*/  
  262.                 long *alp_Duration      /*结果整形指针*/  
  263.          )  
  264. {  
  265.   struct tm ls_DateTime1,ls_DateTime2;  
  266.   time_t    lt_DateTime1,lt_DateTime2;  
  267.   long    ll_Duration;  
  268.   
  269.   memset((void *) &ls_DateTime1, 0, sizeof(struct tm));  
  270.   memset((void *) &ls_DateTime2, 0, sizeof(struct tm));  
  271.   
  272.   /*转换为tm结构变量*/  
  273.   strptime( azp_DateTime1,"%Y-%m-%d %T", &ls_DateTime1 );  
  274.   strptime( azp_DateTime2,"%Y-%m-%d %T", &ls_DateTime2 );  
  275.   
  276.   /*将结果转换为字串*/  
  277.   if  (( lt_DateTime1 = mktime( &ls_DateTime1 )) == (time_t)-1 )  
  278.   {  
  279.     return( -1 );  
  280.   }  
  281.   if  (( lt_DateTime2 = mktime( &ls_DateTime2 )) == (time_t)-1 )  
  282.   {  
  283.     return( -1 );  
  284.   }  
  285.     
  286.   /*将比较结果写入目标缓冲*/  
  287.   *alp_Duration = (long)difftime( lt_DateTime1,lt_DateTime2 );  
  288.     
  289.   return( 0 );  
  290. }  
  291.   
  292.   
  293. int main()  
  294. {  
  295.   
  296.     char curtime[20]={0};  
  297.     char lasttime[20]={0};  
  298.     long li_dur = 0;  
  299.     ThreadPool::Instance().Init(3);  
  300.      
  301.     int i;  
  302.   
  303.     int *workingnum = (int *) malloc (sizeof (int) * 10);  
  304.   
  305.     GetCurrentTime(curtime);  
  306.     //printf("curtime=%s\n",curtime);  
  307.     while(1)  
  308.     {     
  309.         GetCurrentTime(lasttime);  
  310.   
  311.           
  312.         DateTimeCmp(lasttime,curtime,&li_dur);  
  313.   
  314.         //printf("li_dur=%d\n",li_dur);  
  315.         if (li_dur > 10)  
  316.         {  
  317.             for (i = 0; i < 10; i++)  
  318.             {  
  319.                 workingnum[i] = i;  
  320.                 ThreadPool::Instance().add(task_run, &workingnum[i]);   
  321.                 ThreadPool::Instance().GetTask(i);  
  322.                 sleep(1);     
  323.             }  
  324.   
  325.             strcpy(curtime,lasttime);  
  326.         }  
  327.     }  
  328.   
  329.       
  330.   
  331.     /*等待所有任务完成*/  
  332.      sleep (10);  
  333.     /*销毁线程池*/  
  334.      //ThreadPool::Instance().clear();  
  335.   
  336.   
  337.      free (workingnum);  
  338.     return 0;  
  339.   
  340. }  
原创粉丝点击