成人免费xxxxx在线视频软件_久久精品久久久_亚洲国产精品久久久_天天色天天色_亚洲人成一区_欧美一级欧美三级在线观看

我們一起手擼一個線程池

開發 項目管理
見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

參數流程類型

2024-12-10 00:00:25

2025-02-28 08:46:24

框架微服務架構

2021-10-04 09:29:41

對象池線程池

2024-08-29 09:18:55

2024-06-04 07:52:04

2025-01-09 10:57:54

2022-08-29 07:48:27

文件數據參數類型

2024-08-12 15:55:51

2024-08-02 09:49:35

Spring流程Tomcat

2024-06-17 11:59:39

2021-11-15 11:03:09

接口壓測工具

2023-07-16 22:57:38

代碼場景業務

2021-12-14 07:40:07

多線程面試CPU

2023-10-31 09:04:21

CPU調度Java

2021-12-30 06:59:27

視頻通話網頁

2024-02-20 21:34:16

循環GolangGo

2021-07-28 07:53:20

Github ActiDotnet 應用

2022-01-17 06:59:40

Grep指令linux

2021-08-27 07:06:10

IOJava抽象
點贊
收藏

51CTO技術棧公眾號

主站蜘蛛池模板: 成人免费网站视频 | 成人精品一区二区三区中文字幕 | 97人人超碰 | 亚洲国产精品久久 | 超碰超碰 | 国产精品日韩欧美一区二区三区 | 91免费在线播放 | www.欧美.com| 国产精品大全 | 视频在线日韩 | 7777在线视频免费播放 | 日韩欧美一区二区三区四区 | 亚洲逼院 | 午夜国产羞羞视频免费网站 | 欧美淫片| 午夜精品久久久久久久 | 国产精品久久久久久久久久久久 | 在线不卡一区 | 免费的av网站 | 成人av网站在线观看 | 91国内视频在线 | 91av在线视频观看 | 久久婷婷色 | 中文字幕 在线观看 | 日韩在线观看中文字幕 | 精品欧美一区二区三区久久久 | 在线中文字幕国产 | 免费一级片 | 超碰伊人 | 国产乱码精品一区二区三区忘忧草 | 天天干夜夜操 | 高清亚洲 | 精品中文字幕一区 | 亚洲人成人网 | 国产精品视频网站 | 色婷婷一区二区三区四区 | 国产激情91久久精品导航 | 免费一区二区三区在线视频 | 中文字幕 国产 | 日韩美av | 综合中文字幕 |