5.1 线程池V1.0 基础版本

1 初始化线程池

确定线程数量,并做好互斥访问

2 启动所以线程

std::vector<std::thread *> threads_;

  1. unique_lock<mutex> lock(mutex_);
  2. for(int i = 0;i < thread_num_; i++) {
  3. auth th = new thread(&XThreadPool::Run, this);
  4. threads_.push_back(th);
  5. }

3 准备好任务处理基类和插入任务

  1. class XTask
  2. {
  3. public:
  4. // 执行具体的任务
  5. virtual int Run() = 0;
  6. }

存储任务的列表

  1. std::list<XTask*> tasks_;

插入任务,通知线程池处理

  1. unique_lock<mutex> lock(mutex_);
  2. tasks_.push_back(task);
  3. condition_.notify_one();

4 获取任务接口

通过条件变量堵塞等待任务

  1. // 获取任务
  2. XTaskType XThreadPool::GetTask(){
  3. unique_lock<mutex> lock(mutex_);
  4. if(tasks_.empty()){
  5. condition_.wait(lock); // 阻塞 等待通知
  6. }
  7. if(is_exit_) {
  8. return nullptr;
  9. }
  10. if(tasks_.empty()){
  11. return nullptr;
  12. }
  13. auto task = tasks_.front();
  14. tasks_.pop_front();
  15. return task;
  16. }

5 执行任务线程入口函数

  1. void XThread::Run(){
  2. while(!IsExit()){
  3. // 获取任务
  4. autotask= GetTask();
  5. if(!task){
  6. continue;
  7. }
  8. try{
  9. task->Run();
  10. }catch(...){
  11. cerr << "XThread::Run() exception" << endl;
  12. }
  13. }
  14. }