Chinaunix首页 | 论坛 | 博客
  • 博客访问: 324804
  • 博文数量: 78
  • 博客积分: 2536
  • 博客等级: 少校
  • 技术积分: 600
  • 用 户 组: 普通用户
  • 注册时间: 2008-04-29 01:50
文章分类

全部博文(78)

文章存档

2011年(1)

2010年(17)

2009年(52)

2008年(8)

我的朋友

分类: C/C++

2010-10-27 13:15:23

线程池:简单地说,线程池 就是预先创建好一批线程,方便、快速地处理收到的业务。比起传统的到来一个任务,即时创建一个线程来处理,节省了线程的创建和回收的开销,响应更快,效率更高。

 

在linux中,使用的是posix线程库,首先介绍几个常用的函数:

1 线程的创建和取消函数

pthread_create

创建线程

pthread_join

合并线程

pthread_cancel

取消线程

2 线程同步函数

pthread_mutex_lock

pthread_mutex_unlock

pthread_cond_signal

pthread_cond_wait

 

关于函数的详细说明,参考man手册

 

线程池的实现:

线程池的实现主要分为三部分,线程的创建、添加任务到线程池中、工作线程从任务队列中取出任务进行处理。

主要有两个类来实现,CTask,CThreadPool

/**
执行任务的类,设置任务数据并执行
**/

C代码 
  1. class CTask  
  2. {  
  3. protected:  
  4.  string m_strTaskName;  //任务的名称  
  5.  void* m_ptrData;       //要执行的任务的具体数据  
  6. public:  
  7.  CTask(){}  
  8.  CTask(string taskName)  
  9.  {  
  10.   this->m_strTaskName = taskName;  
  11.   m_ptrData = NULL;  
  12.  }  
  13.  virtual int Run()= 0;  
  14.  void SetData(void* data);    //设置任务数据  
  15. };  

 

任务类是个虚类,所有的任务要从CTask类中继承 ,实现run接口,run接口中需要实现的就是具体解析任务的逻辑。m_ptrData是指向任务数据的指针,可以是简单数据类型,也可以是自定义的复杂数据类型。

 

线程池类

/**
线程池
**/

Java代码 
  1. class CThreadPool  
  2. {  
  3. private:  
  4.  vector m_vecTaskList;         //任务列表  
  5.  int m_iThreadNum;                            //线程池中启动的线程数             
  6.  static vector m_vecIdleThread;   //当前空闲的线程集合  
  7.  static vector m_vecBusyThread;   //当前正在执行的线程集合  
  8.  static pthread_mutex_t m_pthreadMutex;    //线程同步锁  
  9.  static pthread_cond_t m_pthreadCond;    //线程同步的条件变量  
  10. protected:  
  11.  static void* ThreadFunc(void * threadData); //新线程的线程函数  
  12.  static int MoveToIdle(pthread_t tid);   //线程执行结束后,把自己放入到空闲线程中  
  13.  static int MoveToBusy(pthread_t tid);   //移入到忙碌线程中去  
  14.  int Create();          //创建所有的线程  
  15. public:  
  16.  CThreadPool(int threadNum);  
  17.  int AddTask(CTask *task);      //把任务添加到线程池中  
  18.  int StopAll();  
  19. };  

 

当线程池对象创建后,启动一批线程,并把所有的线程放入空闲列表中,当有任务到达时,某一个线程取出任务并进行处理。

线程之间的同步用线程锁和条件变量。

这个类的对外接口有两个:

AddTask函数把任务添加到线程池的任务列表中,并通知线程进行处理。当任务到到时,把任务放入m_vecTaskList任务列表中,并用pthread_cond_signal唤醒一个线程进行处理。

StopAll函数停止所有的线程

 

Cpp代码 管理员在2009年8月13日编辑了该文章文章。
-->
阅读(1774) | 评论(1) | 转发(0) |
给主人留下些什么吧!~~

chinaunix网友2010-10-28 17:52:03

很好的, 收藏了 推荐一个博客,提供很多免费软件编程电子书下载: http://free-ebooks.appspot.com