linux c++线程池的实现

http://blog.csdn.net/zhoubl668/article/details/8927090?t=1473221020107

线程池的原理大家都知道,直接上代码了^_^

Thread.h

[cpp]  view plain copy
  1. #ifndef __THREAD_H   
  2. #define __THREAD_H   
  3.   
  4. #include <vector>   
  5. #include <string>   
  6. #include <pthread.h>   
  7.   
  8. using namespace std;  
  9.   
  10. /** 
  11.  * 执行任务的类,设置任务数据并执行 
  12.  */  
  13. class CTask  
  14. {  
  15. protected:  
  16.     string m_strTaskName;  /** 任务的名称 */  
  17.     void* m_ptrData;       /** 要执行的任务的具体数据 */  
  18. public:  
  19.     CTask(){}  
  20.     CTask(string taskName)  
  21.     {  
  22.         m_strTaskName = taskName;  
  23.         m_ptrData = NULL;  
  24.     }  
  25.     virtual int Run()= 0;  
  26.     void SetData(void* data);    /** 设置任务数据 */  
  27.   
  28. public:  
  29.     virtual ~CTask(){}  
  30. };  
  31.   
  32. /** 
  33.  * 线程池管理类的实现 
  34.  */  
  35. class CThreadPool  
  36. {  
  37. private:  
  38.     static  vector<CTask*> m_vecTaskList;     /** 任务列表 */  
  39.     static  bool shutdown;                    /** 线程退出标志 */           
  40.     int     m_iThreadNum;                     /** 线程池中启动的线程数 */  
  41.     pthread_t   *pthread_id;  
  42.       
  43.     static pthread_mutex_t m_pthreadMutex;    /** 线程同步锁 */  
  44.     static pthread_cond_t m_pthreadCond;      /** 线程同步的条件变量 */  
  45.   
  46. protected:  
  47.     static void* ThreadFunc(void * threadData); /** 新线程的线程回调函数 */  
  48.     static int MoveToIdle(pthread_t tid);       /** 线程执行结束后,把自己放入到空闲线程中 */  
  49.     static int MoveToBusy(pthread_t tid);       /** 移入到忙碌线程中去 */  
  50.       
  51.     int Create();          /** 创建线程池中的线程 */  
  52.   
  53. public:  
  54.     CThreadPool(int threadNum = 10);  
  55.     int AddTask(CTask *task);      /** 把任务添加到任务队列中 */  
  56.     int StopAll();                 /** 使线程池中的线程退出 */  
  57.     int getTaskSize();             /** 获取当前任务队列中的任务数 */  
  58. };  
  59.   
  60. #endif  
[cpp]  view plain  copy
  1. #ifndef __THREAD_H  
  2. #define __THREAD_H  
  3.   
  4. #include <vector>  
  5. #include <string>  
  6. #include <pthread.h>  
  7.   
  8. using namespace std;  
  9.   
  10. /** 
  11.  * 执行任务的类,设置任务数据并执行 
  12.  */  
  13. class CTask  
  14. {  
  15. protected:  
  16.     string m_strTaskName;  /** 任务的名称 */  
  17.     void* m_ptrData;       /** 要执行的任务的具体数据 */  
  18. public:  
  19.     CTask(){}  
  20.     CTask(string taskName)  
  21.     {  
  22.         m_strTaskName = taskName;  
  23.         m_ptrData = NULL;  
  24.     }  
  25.     virtual int Run()= 0;  
  26.     void SetData(void* data);    /** 设置任务数据 */  
  27.   
  28. public:  
  29.     virtual ~CTask(){}  
  30. };  
  31.   
  32. /** 
  33.  * 线程池管理类的实现 
  34.  */  
  35. class CThreadPool  
  36. {  
  37. private:  
  38.     static  vector<CTask*> m_vecTaskList;     /** 任务列表 */  
  39.     static  bool shutdown;                    /** 线程退出标志 */           
  40.     int     m_iThreadNum;                     /** 线程池中启动的线程数 */  
  41.     pthread_t   *pthread_id;  
  42.       
  43.     static pthread_mutex_t m_pthreadMutex;    /** 线程同步锁 */  
  44.     static pthread_cond_t m_pthreadCond;      /** 线程同步的条件变量 */  
  45.   
  46. protected:  
  47.     static void* ThreadFunc(void * threadData); /** 新线程的线程回调函数 */  
  48.     static int MoveToIdle(pthread_t tid);       /** 线程执行结束后,把自己放入到空闲线程中 */  
  49.     static int MoveToBusy(pthread_t tid);       /** 移入到忙碌线程中去 */  
  50.       
  51.     int Create();          /** 创建线程池中的线程 */  
  52.   
  53. public:  
  54.     CThreadPool(int threadNum = 10);  
  55.     int AddTask(CTask *task);      /** 把任务添加到任务队列中 */  
  56.     int StopAll();                 /** 使线程池中的线程退出 */  
  57.     int getTaskSize();             /** 获取当前任务队列中的任务数 */  
  58. };  
  59.   
  60. #endif  

 

实现文件

Thread.cpp

[cpp]  view plain copy
  1. #include "Thread.h"   
  2. #include <iostream>   
  3.   
  4. void CTask::SetData(void * data)  
  5. {  
  6.     m_ptrData = data;  
  7. }  
  8.   
  9. vector<CTask*> CThreadPool::m_vecTaskList;         //任务列表   
  10. bool CThreadPool::shutdown = false;  
  11.       
  12. pthread_mutex_t CThreadPool::m_pthreadMutex = PTHREAD_MUTEX_INITIALIZER;   
  13. pthread_cond_t CThreadPool::m_pthreadCond = PTHREAD_COND_INITIALIZER;  
  14.   
  15. /** 
  16.  * 线程池管理类构造函数 
  17.  */  
  18. CThreadPool::CThreadPool(int threadNum)  
  19. {  
  20.     this->m_iThreadNum = threadNum;  
  21.     cout << "I will create " << threadNum << " threads" << endl;  
  22.     Create();  
  23. }  
  24.   
  25. /** 
  26.  * 线程回调函数 
  27.  */  
  28. void* CThreadPool::ThreadFunc(void* threadData)  
  29. {  
  30.     pthread_t tid = pthread_self();  
  31.     while (1)  
  32.     {  
  33.         pthread_mutex_lock(&m_pthreadMutex);  
  34.         while (m_vecTaskList.size() == 0 && !shutdown)  
  35.         {  
  36.             pthread_cond_wait(&m_pthreadCond, &m_pthreadMutex);  
  37.         }  
  38.           
  39.         if (shutdown)  
  40.         {  
  41.             pthread_mutex_unlock(&m_pthreadMutex);  
  42.             printf("thread %lu will exit/n", pthread_self());  
  43.             pthread_exit(NULL);   
  44.         }  
  45.           
  46.         printf("tid %lu run/n", tid);  
  47.         vector<CTask*>::iterator iter = m_vecTaskList.begin();  
  48.           
  49.         /** 
  50.         * 取出一个任务并处理之 
  51.         */  
  52.         CTask* task = *iter;  
  53.         if (iter != m_vecTaskList.end())  
  54.         {  
  55.             task = *iter;  
  56.             m_vecTaskList.erase(iter);  
  57.         }  
  58.           
  59.         pthread_mutex_unlock(&m_pthreadMutex);  
  60.           
  61.         task->Run(); /** 执行任务 */  
  62.         printf("tid:%lu idle/n", tid);  
  63.     }  
  64.     return (void*)0;  
  65. }  
  66.   
  67. /** 
  68.  * 往任务队列里边添加任务并发出线程同步信号 
  69.  */  
  70. int CThreadPool::AddTask(CTask *task)  
  71. {  
  72.     pthread_mutex_lock(&m_pthreadMutex);  
  73.     this->m_vecTaskList.push_back(task);  
  74.     pthread_mutex_unlock(&m_pthreadMutex);  
  75.     pthread_cond_signal(&m_pthreadCond);  
  76.     return 0;  
  77. }  
  78.   
  79. /** 
  80.  * 创建线程 
  81.  */  
  82. int CThreadPool::Create()  
  83. {  
  84.     pthread_id = (pthread_t*)malloc(sizeof(pthread_t) * m_iThreadNum);  
  85.     for(int i = 0; i < m_iThreadNum; i++)  
  86.     {  
  87.         pthread_create(&pthread_id[i], NULL, ThreadFunc, NULL);  
  88.     }  
  89.     return 0;  
  90. }  
  91.   
  92. /** 
  93.  * 停止所有线程 
  94.  */  
  95. int CThreadPool::StopAll()  
  96. {  
  97.     /** 避免重复调用 */  
  98.     if (shutdown)  
  99.     {  
  100.         return -1;    
  101.     }  
  102.     printf("Now I will end all threads!!/n");  
  103.     /** 唤醒所有等待线程,线程池要销毁了 */  
  104.     shutdown = true;  
  105.     pthread_cond_broadcast(&m_pthreadCond);  
  106.       
  107.     /** 阻塞等待线程退出,否则就成僵尸了 */  
  108.     for (int i = 0; i < m_iThreadNum; i++)  
  109.     {  
  110.         pthread_join(pthread_id[i], NULL);    
  111.     }  
  112.       
  113.     free(pthread_id);  
  114.     pthread_id = NULL;  
  115.       
  116.     /** 销毁条件变量和互斥体 */  
  117.     pthread_mutex_destroy(&m_pthreadMutex);  
  118.     pthread_cond_destroy(&m_pthreadCond);  
  119.       
  120.     return 0;  
  121. }  
  122.   
  123. /** 
  124.  * 获取当前队列中任务数 
  125.  */  
  126. int CThreadPool::getTaskSize()  
  127. {  
  128.     return m_vecTaskList.size();      
  129. }  
[cpp]  view plain  copy
  1. #include "Thread.h"  
  2. #include <iostream>  
  3.   
  4. void CTask::SetData(void * data)  
  5. {  
  6.     m_ptrData = data;  
  7. }  
  8.   
  9. vector<CTask*> CThreadPool::m_vecTaskList;         //任务列表  
  10. bool CThreadPool::shutdown = false;  
  11.       
  12. pthread_mutex_t CThreadPool::m_pthreadMutex = PTHREAD_MUTEX_INITIALIZER;   
  13. pthread_cond_t CThreadPool::m_pthreadCond = PTHREAD_COND_INITIALIZER;  
  14.   
  15. /** 
  16.  * 线程池管理类构造函数 
  17.  */  
  18. CThreadPool::CThreadPool(int threadNum)  
  19. {  
  20.     this->m_iThreadNum = threadNum;  
  21.     cout << "I will create " << threadNum << " threads" << endl;  
  22.     Create();  
  23. }  
  24.   
  25. /** 
  26.  * 线程回调函数 
  27.  */  
  28. void* CThreadPool::ThreadFunc(void* threadData)  
  29. {  
  30.     pthread_t tid = pthread_self();  
  31.     while (1)  
  32.     {  
  33.         pthread_mutex_lock(&m_pthreadMutex);  
  34.         while (m_vecTaskList.size() == 0 && !shutdown)  
  35.         {  
  36.             pthread_cond_wait(&m_pthreadCond, &m_pthreadMutex);  
  37.         }  
  38.           
  39.         if (shutdown)  
  40.         {  
  41.             pthread_mutex_unlock(&m_pthreadMutex);  
  42.             printf("thread %lu will exit/n", pthread_self());  
  43.             pthread_exit(NULL);   
  44.         }  
  45.           
  46.         printf("tid %lu run/n", tid);  
  47.         vector<CTask*>::iterator iter = m_vecTaskList.begin();  
  48.           
  49.         /** 
  50.         * 取出一个任务并处理之 
  51.         */  
  52.         CTask* task = *iter;  
  53.         if (iter != m_vecTaskList.end())  
  54.         {  
  55.             task = *iter;  
  56.             m_vecTaskList.erase(iter);  
  57.         }  
  58.           
  59.         pthread_mutex_unlock(&m_pthreadMutex);  
  60.           
  61.         task->Run(); /** 执行任务 */  
  62.         printf("tid:%lu idle/n", tid);  
  63.     }  
  64.     return (void*)0;  
  65. }  
  66.   
  67. /** 
  68.  * 往任务队列里边添加任务并发出线程同步信号 
  69.  */  
  70. int CThreadPool::AddTask(CTask *task)  
  71. {  
  72.     pthread_mutex_lock(&m_pthreadMutex);  
  73.     this->m_vecTaskList.push_back(task);  
  74.     pthread_mutex_unlock(&m_pthreadMutex);  
  75.     pthread_cond_signal(&m_pthreadCond);  
  76.     return 0;  
  77. }  
  78.   
  79. /** 
  80.  * 创建线程 
  81.  */  
  82. int CThreadPool::Create()  
  83. {  
  84.     pthread_id = (pthread_t*)malloc(sizeof(pthread_t) * m_iThreadNum);  
  85.     for(int i = 0; i < m_iThreadNum; i++)  
  86.     {  
  87.         pthread_create(&pthread_id[i], NULL, ThreadFunc, NULL);  
  88.     }  
  89.     return 0;  
  90. }  
  91.   
  92. /** 
  93.  * 停止所有线程 
  94.  */  
  95. int CThreadPool::StopAll()  
  96. {  
  97.     /** 避免重复调用 */  
  98.     if (shutdown)  
  99.     {  
  100.         return -1;    
  101.     }  
  102.     printf("Now I will end all threads!!/n");  
  103.     /** 唤醒所有等待线程,线程池要销毁了 */  
  104.     shutdown = true;  
  105.     pthread_cond_broadcast(&m_pthreadCond);  
  106.       
  107.     /** 阻塞等待线程退出,否则就成僵尸了 */  
  108.     for (int i = 0; i < m_iThreadNum; i++)  
  109.     {  
  110.         pthread_join(pthread_id[i], NULL);    
  111.     }  
  112.       
  113.     free(pthread_id);  
  114.     pthread_id = NULL;  
  115.       
  116.     /** 销毁条件变量和互斥体 */  
  117.     pthread_mutex_destroy(&m_pthreadMutex);  
  118.     pthread_cond_destroy(&m_pthreadCond);  
  119.       
  120.     return 0;  
  121. }  
  122.   
  123. /** 
  124.  * 获取当前队列中任务数 
  125.  */  
  126. int CThreadPool::getTaskSize()  
  127. {  
  128.     return m_vecTaskList.size();      
  129. }  

 

main函数文件

[cpp]  view plain copy
  1. #include "Thread.h"   
  2. #include <iostream>   
  3.   
  4. class CMyTask: public CTask  
  5. {  
  6. public:  
  7.     CMyTask(){}  
  8.       
  9.     inline int Run()  
  10.     {  
  11.         printf("%s/n", (char*)this->m_ptrData);  
  12.         sleep(10);  
  13.         return 0;  
  14.     }  
  15. };  
  16.   
  17. int main()  
  18. {  
  19.     CMyTask taskObj;  
  20.       
  21.     char szTmp[] = "this is the first thread running";  
  22.     taskObj.SetData((void*)szTmp);  
  23.     CThreadPool threadPool(10);  
  24.       
  25.     for(int i = 0; i < 20; i++)  
  26.     {  
  27.         threadPool.AddTask(&taskObj);  
  28.     }  
  29.       
  30.     while(1)  
  31.     {  
  32.         printf("there are still %d tasks need to handle/n", threadPool.getTaskSize());  
  33.         if (threadPool.getTaskSize() == 0)  
  34.         {  
  35.             if (threadPool.StopAll() == -1)  
  36.             {     
  37.                 printf("Now I will exit from main/n");  
  38.                 exit(0);  
  39.             }  
  40.         }  
  41.         sleep(2);  
  42.     }  
  43.       
  44.     return 0;  
  45. }  
[cpp]  view plain  copy
  1. #include "Thread.h"  
  2. #include <iostream>  
  3.   
  4. class CMyTask: public CTask  
  5. {  
  6. public:  
  7.     CMyTask(){}  
  8.       
  9.     inline int Run()  
  10.     {  
  11.         printf("%s/n", (char*)this->m_ptrData);  
  12.         sleep(10);  
  13.         return 0;  
  14.     }  
  15. };  
  16.   
  17. int main()  
  18. {  
  19.     CMyTask taskObj;  
  20.       
  21.     char szTmp[] = "this is the first thread running";  
  22.     taskObj.SetData((void*)szTmp);  
  23.     CThreadPool threadPool(10);  
  24.       
  25.     for(int i = 0; i < 20; i++)  
  26.     {  
  27.         threadPool.AddTask(&taskObj);  
  28.     }  
  29.       
  30.     while(1)  
  31.     {  
  32.         printf("there are still %d tasks need to handle/n", threadPool.getTaskSize());  
  33.         if (threadPool.getTaskSize() == 0)  
  34.         {  
  35.             if (threadPool.StopAll() == -1)  
  36.             {     
  37.                 printf("Now I will exit from main/n");  
  38.                 exit(0);  
  39.             }  
  40.         }  
  41.         sleep(2);  
  42.     }  
  43.       
  44.     return 0;  
  45. }  

 

Makefile文件

[cpp]  view plain copy
  1. CC := g++  
  2. TARGET := threadpool  
  3. INCLUDE := -I./  
  4. LIBS := -lpthread   
  5.   
  6. # C++语言编译参数   
  7. CXXFLAGS := -g -Wall -D_REENTRANT   
  8.   
  9. # C预处理参数   
  10. # CPPFLAGS :=    
  11.   
  12. OBJECTS := test.o Thread.o   
  13.   
  14. $(TARGET): $(OBJECTS)   
  15.     $(CC) -o $(TARGET) $(OBJECTS) $(LIBS)   
  16.   
  17. # $@表示所有目标集   
  18. %.o:%.cpp   
  19.     $(CC) -c $(CXXFLAGS) $(INCLUDE) $< -o $@   
  20.   
  21. .PHONY : clean  
  22. clean:   
  23.     -rm -f $(OBJECTS) $(TARGET)  
[cpp]  view plain  copy
  1. CC := g++  
  2. TARGET := threadpool  
  3. INCLUDE := -I./  
  4. LIBS := -lpthread   
  5.   
  6. # C++语言编译参数  
  7. CXXFLAGS := -g -Wall -D_REENTRANT   
  8.   
  9. # C预处理参数  
  10. # CPPFLAGS :=   
  11.   
  12. OBJECTS := test.o Thread.o   
  13.   
  14. $(TARGET): $(OBJECTS)   
  15.     $(CC) -o $(TARGET) $(OBJECTS) $(LIBS)   
  16.   
  17. # $@表示所有目标集  
  18. %.o:%.cpp   
  19.     $(CC) -c $(CXXFLAGS) $(INCLUDE) $< -o $@   
  20.   
  21. .PHONY : clean  
  22. clean:   
  23.     -rm -f $(OBJECTS) $(TARGET)  

 

在Linux上的输出:

[xhtml]  view plain copy
  1. I will create 10 threads  
  2. there are still 10 tasks need to handle  
  3. tid 3086535568 run  
  4. this is the first thread running  
  5. tid 3084434320 run  
  6. this is the first thread running  
  7. tid 3082333072 run  
  8. this is the first thread running  
  9. tid 3080231824 run  
  10. this is the first thread running  
  11. tid 3078130576 run  
  12. this is the first thread running  
  13. tid 3076029328 run  
  14. this is the first thread running  
  15. tid 3073928080 run  
  16. this is the first thread running  
  17. tid 3071826832 run  
  18. this is the first thread running  
  19. tid 3069725584 run  
  20. this is the first thread running  
  21. tid 3067624336 run  
  22. this is the first thread running  
  23. there are still 0 tasks need to handle  
  24. Now I will end all threads!!  
  25. tid:3086535568 idle  
  26. tid:3078130576 idle  
  27. thread 3078130576 will exit  
  28. tid:3076029328 idle  
  29. thread 3076029328 will exit  
  30. tid:3073928080 idle  
  31. thread 3073928080 will exit  
  32. tid:3071826832 idle  
  33. thread 3071826832 will exit  
  34. tid:3069725584 idle  
  35. thread 3069725584 will exit  
  36. tid:3067624336 idle  
  37. thread 3067624336 will exit  
  38. tid:3084434320 idle  
  39. thread 3084434320 will exit  
  40. thread 3086535568 will exit  
  41. tid:3082333072 idle  
  42. thread 3082333072 will exit  
  43. tid:3080231824 idle  
  44. thread 3080231824 will exit  
  45. there are still 0 tasks need to handle  
  46. Now I will exit from main  
[xhtml]  view plain  copy
  1. I will create 10 threads  
  2. there are still 10 tasks need to handle  
  3. tid 3086535568 run  
  4. this is the first thread running  
  5. tid 3084434320 run  
  6. this is the first thread running  
  7. tid 3082333072 run  
  8. this is the first thread running  
  9. tid 3080231824 run  
  10. this is the first thread running  
  11. tid 3078130576 run  
  12. this is the first thread running  
  13. tid 3076029328 run  
  14. this is the first thread running  
  15. tid 3073928080 run  
  16. this is the first thread running  
  17. tid 3071826832 run  
  18. this is the first thread running  
  19. tid 3069725584 run  
  20. this is the first thread running  
  21. tid 3067624336 run  
  22. this is the first thread running  
  23. there are still 0 tasks need to handle  
  24. Now I will end all threads!!  
  25. tid:3086535568 idle  
  26. tid:3078130576 idle  
  27. thread 3078130576 will exit  
  28. tid:3076029328 idle  
  29. thread 3076029328 will exit  
  30. tid:3073928080 idle  
  31. thread 3073928080 will exit  
  32. tid:3071826832 idle  
  33. thread 3071826832 will exit  
  34. tid:3069725584 idle  
  35. thread 3069725584 will exit  
  36. tid:3067624336 idle  
  37. thread 3067624336 will exit  
  38. tid:3084434320 idle  
  39. thread 3084434320 will exit  
  40. thread 3086535568 will exit  
  41. tid:3082333072 idle  
  42. thread 3082333072 will exit  
  43. tid:3080231824 idle  
  44. thread 3080231824 will exit  
  45. there are still 0 tasks need to handle  
  46. Now I will exit from main  

 


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值