我们一起手撸一个线程池

开发 项目管理
见AddThread()函数,默认会创建Core线程,也可以选择创建Cache线程,线程内部会有一个死循环,不停的等待任务,有任务到来时就会执行,同时内部会判断是否是Cache线程,如果是Cache线程,timeout时间内没有任务执行就会自动退出循环,线程结束。

[[431420]]

本文转载自微信公众号「程序喵大人」,作者程序喵大人 。转载本文请联系程序喵大人公众号。

之前分享过一次手写线程池 - C语言版,然后有朋友问是否有C++线程池实现的文章:

其实关于C++线程池的文章我好久以前写过,但估计很多新朋友都没有看到过,这里也重新发一下!

本人在开发过程中经常会遇到需要使用线程池的需求,但查了一圈发现在C++中完备的线程池第三方库还是比较少的,于是打算自己搞一个,链接地址文章最后附上,目前还只是初版,可能还有很多问题,望各位指正。

线程池都需要什么功能?

个人认为线程池需要支持以下几个基本功能:

  • 核心线程数(core_threads):线程池中拥有的最少线程个数,初始化时就会创建好的线程,常驻于线程池。
  • 最大线程个数(max_threads):线程池中拥有的最大线程个数,max_threads>=core_threads,当任务的个数太多线程池执行不过来时,内部就会创建更多的线程用于执行更多的任务,内部线程数不会超过max_threads,多创建出来的线程在一段时间内没有执行任务则会自动被回收掉,最终线程个数保持在核心线程数。
  • 超时时间(time_out):如上所述,多创建出来的线程在time_out时间内没有执行任务就会被回收。
  • 可获取当前线程池中线程的总个数。
  • 可获取当前线程池中空闲线程的个数。
  • 开启线程池功能的开关。
  • 关闭线程池功能的开关,可以选择是否立即关闭,立即关闭线程池时,当前线程池里缓存的任务不会被执行。

如何实现线程池?下面是自己实现的线程池逻辑。

线程池中主要的数据结构

1. 链表或者数组:用于存储线程池中的线程。

2. 队列:用于存储需要放入线程池中执行的任务。

3. 条件变量:当有任务需要执行时,用于通知正在等待的线程从任务队列中取出任务执行。

代码如下:

  1. class ThreadPool { 
  2.  public
  3.   using PoolSeconds = std::chrono::seconds; 
  4.  
  5.   /** 线程池的配置 
  6.    * core_threads: 核心线程个数,线程池中最少拥有的线程个数,初始化就会创建好的线程,常驻于线程池 
  7.    * 
  8.    * max_threads: >=core_threads,当任务的个数太多线程池执行不过来时, 
  9.    * 内部就会创建更多的线程用于执行更多的任务,内部线程数不会超过max_threads 
  10.    * 
  11.    * max_task_size: 内部允许存储的最大任务个数,暂时没有使用 
  12.    * 
  13.    * time_out: Cache线程的超时时间,Cache线程指的是max_threads-core_threads的线程, 
  14.    * 当time_out时间内没有执行任务,此线程就会被自动回收 
  15.    */ 
  16.   struct ThreadPoolConfig { 
  17.       int core_threads; 
  18.       int max_threads; 
  19.       int max_task_size; 
  20.       PoolSeconds time_out; 
  21.   }; 
  22.  
  23.   /** 
  24.    * 线程的状态:有等待、运行、停止 
  25.    */ 
  26.   enum class ThreadState { kInit = 0, kWaiting = 1, kRunning = 2, kStop = 3 }; 
  27.  
  28.   /** 
  29.    * 线程的种类标识:标志该线程是核心线程还是Cache线程,Cache是内部为了执行更多任务临时创建出来的 
  30.    */ 
  31.   enum class ThreadFlag { kInit = 0, kCore = 1, kCache = 2 }; 
  32.  
  33.   using ThreadPtr = std::shared_ptr<std::thread>; 
  34.   using ThreadId = std::atomic<int>; 
  35.   using ThreadStateAtomic = std::atomic<ThreadState>; 
  36.   using ThreadFlagAtomic = std::atomic<ThreadFlag>; 
  37.  
  38.   /** 
  39.    * 线程池中线程存在的基本单位,每个线程都有个自定义的ID,有线程种类标识和状态 
  40.    */ 
  41.   struct ThreadWrapper { 
  42.       ThreadPtr ptr; 
  43.       ThreadId id; 
  44.       ThreadFlagAtomic flag; 
  45.       ThreadStateAtomic state; 
  46.  
  47.       ThreadWrapper() { 
  48.           ptr = nullptr; 
  49.           id = 0; 
  50.           state.store(ThreadState::kInit); 
  51.       } 
  52.   }; 
  53.   using ThreadWrapperPtr = std::shared_ptr<ThreadWrapper>; 
  54.   using ThreadPoolLock = std::unique_lock<std::mutex>; 
  55.  
  56.  private: 
  57.   ThreadPoolConfig config_; 
  58.  
  59.   std::list<ThreadWrapperPtr> worker_threads_; 
  60.  
  61.   std::queue<std::function<void()>> tasks_; 
  62.   std::mutex task_mutex_; 
  63.   std::condition_variable task_cv_; 
  64.  
  65.   std::atomic<int> total_function_num_; 
  66.   std::atomic<int> waiting_thread_num_; 
  67.   std::atomic<int> thread_id_; // 用于为新创建的线程分配ID 
  68.  
  69.   std::atomic<bool> is_shutdown_now_; 
  70.   std::atomic<bool> is_shutdown_; 
  71.   std::atomic<bool> is_available_; 
  72. }; 

线程池的初始化

在构造函数中将各个成员变量都附初值,同时判断线程池的config是否合法。

  1. ThreadPool(ThreadPoolConfig config) : config_(config) { 
  2.     this->total_function_num_.store(0); 
  3.     this->waiting_thread_num_.store(0); 
  4.  
  5.     this->thread_id_.store(0); 
  6.     this->is_shutdown_.store(false); 
  7.     this->is_shutdown_now_.store(false); 
  8.  
  9.     if (IsValidConfig(config_)) { 
  10.         is_available_.store(true); 
  11.     } else { 
  12.         is_available_.store(false); 
  13.     } 
  14.  
  15. bool IsValidConfig(ThreadPoolConfig config) { 
  16.     if (config.core_threads < 1 || config.max_threads < config.core_threads || config.time_out.count() < 1) { 
  17.         return false
  18.     } 
  19.     return true

如何开启线程池功能?

创建核心线程数个线程,常驻于线程池,等待任务的执行,线程ID由GetNextThreadId()统一分配。

  1. // 开启线程池功能 
  2. bool Start() { 
  3.     if (!IsAvailable()) { 
  4.         return false
  5.     } 
  6.     int core_thread_num = config_.core_threads; 
  7.     cout << "Init thread num " << core_thread_num << endl; 
  8.     while (core_thread_num-- > 0) { 
  9.         AddThread(GetNextThreadId()); 
  10.     } 
  11.     cout << "Init thread end" << endl; 
  12.     return true

如何关闭线程?

这里有两个标志位,is_shutdown_now置为true表示立即关闭线程,is_shutdown置为true则表示先执行完队列里的任务再关闭线程池。

  1. // 关掉线程池,内部还没有执行的任务会继续执行 
  2. void ShutDown() { 
  3.     ShutDown(false); 
  4.     cout << "shutdown" << endl; 
  5.  
  6. // 执行关掉线程池,内部还没有执行的任务直接取消,不会再执行 
  7. void ShutDownNow() { 
  8.     ShutDown(true); 
  9.     cout << "shutdown now" << endl; 
  10.  
  11. // private 
  12. void ShutDown(bool is_now) { 
  13.     if (is_available_.load()) { 
  14.         if (is_now) { 
  15.             this->is_shutdown_now_.store(true); 
  16.         } else { 
  17.             this->is_shutdown_.store(true); 
  18.         } 
  19.         this->task_cv_.notify_all(); 
  20.         is_available_.store(false); 
  21.     } 

如何为线程池添加线程?

见AddThread()函数,默认会创建Core线程,也可以选择创建Cache线程,线程内部会有一个死循环,不停的等待任务,有任务到来时就会执行,同时内部会判断是否是Cache线程,如果是Cache线程,timeout时间内没有任务执行就会自动退出循环,线程结束。

这里还会检查is_shutdown和is_shutdown_now标志,根据两个标志位是否为true来判断是否结束线程。

  1. void AddThread(int id) { AddThread(id, ThreadFlag::kCore); } 
  2.  
  3. void AddThread(int id, ThreadFlag thread_flag) { 
  4.     cout << "AddThread " << id << " flag " << static_cast<int>(thread_flag) << endl; 
  5.     ThreadWrapperPtr thread_ptr = std::make_shared<ThreadWrapper>(); 
  6.     thread_ptr->id.store(id); 
  7.     thread_ptr->flag.store(thread_flag); 
  8.     auto func = [this, thread_ptr]() { 
  9.         for (;;) { 
  10.             std::function<void()> task; 
  11.             { 
  12.                 ThreadPoolLock lock(this->task_mutex_); 
  13.                 if (thread_ptr->state.load() == ThreadState::kStop) { 
  14.                     break; 
  15.                 } 
  16.                 cout << "thread id " << thread_ptr->id.load() << " running start" << endl; 
  17.                 thread_ptr->state.store(ThreadState::kWaiting); 
  18.                 ++this->waiting_thread_num_; 
  19.                 bool is_timeout = false
  20.                 if (thread_ptr->flag.load() == ThreadFlag::kCore) { 
  21.                     this->task_cv_.wait(lock, [this, thread_ptr] { 
  22.                         return (this->is_shutdown_ || this->is_shutdown_now_ || !this->tasks_.empty() || 
  23.                                 thread_ptr->state.load() == ThreadState::kStop); 
  24.                     }); 
  25.                 } else { 
  26.                     this->task_cv_.wait_for(lock, this->config_.time_out, [this, thread_ptr] { 
  27.                         return (this->is_shutdown_ || this->is_shutdown_now_ || !this->tasks_.empty() || 
  28.                                 thread_ptr->state.load() == ThreadState::kStop); 
  29.                     }); 
  30.                     is_timeout = !(this->is_shutdown_ || this->is_shutdown_now_ || !this->tasks_.empty() || 
  31.                                     thread_ptr->state.load() == ThreadState::kStop); 
  32.                 } 
  33.                 --this->waiting_thread_num_; 
  34.                 cout << "thread id " << thread_ptr->id.load() << " running wait end" << endl; 
  35.  
  36.                 if (is_timeout) { 
  37.                     thread_ptr->state.store(ThreadState::kStop); 
  38.                 } 
  39.  
  40.                 if (thread_ptr->state.load() == ThreadState::kStop) { 
  41.                     cout << "thread id " << thread_ptr->id.load() << " state stop" << endl; 
  42.                     break; 
  43.                 } 
  44.                 if (this->is_shutdown_ && this->tasks_.empty()) { 
  45.                     cout << "thread id " << thread_ptr->id.load() << " shutdown" << endl; 
  46.                     break; 
  47.                 } 
  48.                 if (this->is_shutdown_now_) { 
  49.                     cout << "thread id " << thread_ptr->id.load() << " shutdown now" << endl; 
  50.                     break; 
  51.                 } 
  52.                 thread_ptr->state.store(ThreadState::kRunning); 
  53.                 task = std::move(this->tasks_.front()); 
  54.                 this->tasks_.pop(); 
  55.             } 
  56.             task(); 
  57.         } 
  58.         cout << "thread id " << thread_ptr->id.load() << " running end" << endl; 
  59.     }; 
  60.     thread_ptr->ptr = std::make_shared<std::thread>(std::move(func)); 
  61.     if (thread_ptr->ptr->joinable()) { 
  62.         thread_ptr->ptr->detach(); 
  63.     } 
  64.     this->worker_threads_.emplace_back(std::move(thread_ptr)); 

如何将任务放入线程池中执行?

见如下代码,将任务使用std::bind封装成std::function放入任务队列中,任务较多时内部还会判断是否有空闲线程,如果没有空闲线程,会自动创建出最多(max_threads-core_threads)个Cache线程用于执行任务。

  1. // 放在线程池中执行函数 
  2. template <typename F, typename... Args> 
  3. auto Run(F &&f, Args &&... args) -> std::shared_ptr<std::future<std::result_of_t<F(Args...)>>> { 
  4.     if (this->is_shutdown_.load() || this->is_shutdown_now_.load() || !IsAvailable()) { 
  5.         return nullptr; 
  6.     } 
  7.     if (GetWaitingThreadSize() == 0 && GetTotalThreadSize() < config_.max_threads) { 
  8.         AddThread(GetNextThreadId(), ThreadFlag::kCache); 
  9.     } 
  10.  
  11.     using return_type = std::result_of_t<F(Args...)>; 
  12.     auto task = std::make_shared<std::packaged_task<return_type()>>( 
  13.         std::bind(std::forward<F>(f), std::forward<Args>(args)...)); 
  14.     total_function_num_++; 
  15.  
  16.     std::future<return_type> res = task->get_future(); 
  17.     { 
  18.         ThreadPoolLock lock(this->task_mutex_); 
  19.         this->tasks_.emplace([task]() { (*task)(); }); 
  20.     } 
  21.     this->task_cv_.notify_one(); 
  22.     return std::make_shared<std::future<std::result_of_t<F(Args...)>>>(std::move(res)); 

如何获取当前线程池中线程的总个数?

  1. int GetTotalThreadSize() { return this->worker_threads_.size(); } 

如何获取当前线程池中空闲线程的个数?

waiting_thread_num值表示空闲线程的个数,该变量在线程循环内部会更新。

  1. int GetWaitingThreadSize() { return this->waiting_thread_num_.load(); } 

简单的测试代码

  1. int main() { 
  2.     cout << "hello" << endl; 
  3.     ThreadPool pool(ThreadPool::ThreadPoolConfig{4, 5, 6, std::chrono::seconds(4)}); 
  4.     pool.Start(); 
  5.     std::this_thread::sleep_for(std::chrono::seconds(4)); 
  6.     cout << "thread size " << pool.GetTotalThreadSize() << endl; 
  7.     std::atomic<intindex
  8.     index.store(0); 
  9.     std::thread t([&]() { 
  10.         for (int i = 0; i < 10; ++i) { 
  11.             pool.Run([&]() { 
  12.                 cout << "function " << index.load() << endl; 
  13.                 std::this_thread::sleep_for(std::chrono::seconds(4)); 
  14.                 index++; 
  15.             }); 
  16.             // std::this_thread::sleep_for(std::chrono::seconds(2)); 
  17.         } 
  18.     }); 
  19.     t.detach(); 
  20.     cout << "=================" << endl; 
  21.  
  22.     std::this_thread::sleep_for(std::chrono::seconds(4)); 
  23.     pool.Reset(ThreadPool::ThreadPoolConfig{4, 4, 6, std::chrono::seconds(4)}); 
  24.     std::this_thread::sleep_for(std::chrono::seconds(4)); 
  25.     cout << "thread size " << pool.GetTotalThreadSize() << endl; 
  26.     cout << "waiting size " << pool.GetWaitingThreadSize() << endl; 
  27.     cout << "---------------" << endl; 
  28.     pool.ShutDownNow(); 
  29.     getchar(); 
  30.     cout << "world" << endl; 
  31.     return 0; 

 

责任编辑:武晓燕 来源: 程序喵大人
相关推荐

2023-07-11 08:34:25

参数流程类型

2021-10-04 09:29:41

对象池线程池

2022-08-29 07:48:27

文件数据参数类型

2021-11-15 11:03:09

接口压测工具

2023-07-16 22:57:38

代码场景业务

2023-10-31 09:04:21

CPU调度Java

2021-12-14 07:40:07

多线程面试CPU

2021-12-30 06:59:27

视频通话网页

2021-05-14 13:30:17

Mybatis分表插件

2022-10-18 07:33:57

Maven构建工具

2021-08-27 07:06:09

DubboDocker技术

2022-03-31 18:59:43

数据库InnoDBMySQL

2023-08-10 08:28:46

网络编程通信

2023-08-04 08:20:56

DockerfileDocker工具

2023-09-10 21:42:31

2023-06-30 08:18:51

敏捷开发模式

2022-05-24 08:21:16

数据安全API

2021-01-12 05:08:49

DHCP协议模型

2022-06-27 08:00:49

hook工具库函数

2021-08-27 07:06:10

IOJava抽象
点赞
收藏

51CTO技术栈公众号