自拍偷在线精品自拍偷,亚洲欧美中文日韩v在线观看不卡

我們一起手?jǐn)]一個線程池

開發(fā) 項目管理
見AddThread()函數(shù),默認(rèn)會創(chuàng)建Core線程,也可以選擇創(chuàng)建Cache線程,線程內(nèi)部會有一個死循環(huán),不停的等待任務(wù),有任務(wù)到來時就會執(zhí)行,同時內(nèi)部會判斷是否是Cache線程,如果是Cache線程,timeout時間內(nèi)沒有任務(wù)執(zhí)行就會自動退出循環(huán),線程結(jié)束。

[[431420]]

本文轉(zhuǎn)載自微信公眾號「程序喵大人」,作者程序喵大人 。轉(zhuǎn)載本文請聯(lián)系程序喵大人公眾號。

之前分享過一次手寫線程池 - C語言版,然后有朋友問是否有C++線程池實現(xiàn)的文章:

其實關(guān)于C++線程池的文章我好久以前寫過,但估計很多新朋友都沒有看到過,這里也重新發(fā)一下!

本人在開發(fā)過程中經(jīng)常會遇到需要使用線程池的需求,但查了一圈發(fā)現(xiàn)在C++中完備的線程池第三方庫還是比較少的,于是打算自己搞一個,鏈接地址文章最后附上,目前還只是初版,可能還有很多問題,望各位指正。

線程池都需要什么功能?

個人認(rèn)為線程池需要支持以下幾個基本功能:

  • 核心線程數(shù)(core_threads):線程池中擁有的最少線程個數(shù),初始化時就會創(chuàng)建好的線程,常駐于線程池。
  • 最大線程個數(shù)(max_threads):線程池中擁有的最大線程個數(shù),max_threads>=core_threads,當(dāng)任務(wù)的個數(shù)太多線程池執(zhí)行不過來時,內(nèi)部就會創(chuàng)建更多的線程用于執(zhí)行更多的任務(wù),內(nèi)部線程數(shù)不會超過max_threads,多創(chuàng)建出來的線程在一段時間內(nèi)沒有執(zhí)行任務(wù)則會自動被回收掉,最終線程個數(shù)保持在核心線程數(shù)。
  • 超時時間(time_out):如上所述,多創(chuàng)建出來的線程在time_out時間內(nèi)沒有執(zhí)行任務(wù)就會被回收。
  • 可獲取當(dāng)前線程池中線程的總個數(shù)。
  • 可獲取當(dāng)前線程池中空閑線程的個數(shù)。
  • 開啟線程池功能的開關(guān)。
  • 關(guān)閉線程池功能的開關(guān),可以選擇是否立即關(guān)閉,立即關(guān)閉線程池時,當(dāng)前線程池里緩存的任務(wù)不會被執(zhí)行。

如何實現(xiàn)線程池?下面是自己實現(xiàn)的線程池邏輯。

線程池中主要的數(shù)據(jù)結(jié)構(gòu)

1. 鏈表或者數(shù)組:用于存儲線程池中的線程。

2. 隊列:用于存儲需要放入線程池中執(zhí)行的任務(wù)。

3. 條件變量:當(dāng)有任務(wù)需要執(zhí)行時,用于通知正在等待的線程從任務(wù)隊列中取出任務(wù)執(zhí)行。

代碼如下:

  1. class ThreadPool { 
  2.  public
  3.   using PoolSeconds = std::chrono::seconds; 
  4.  
  5.   /** 線程池的配置 
  6.    * core_threads: 核心線程個數(shù),線程池中最少擁有的線程個數(shù),初始化就會創(chuàng)建好的線程,常駐于線程池 
  7.    * 
  8.    * max_threads: >=core_threads,當(dāng)任務(wù)的個數(shù)太多線程池執(zhí)行不過來時, 
  9.    * 內(nèi)部就會創(chuàng)建更多的線程用于執(zhí)行更多的任務(wù),內(nèi)部線程數(shù)不會超過max_threads 
  10.    * 
  11.    * max_task_size: 內(nèi)部允許存儲的最大任務(wù)個數(shù),暫時沒有使用 
  12.    * 
  13.    * time_out: Cache線程的超時時間,Cache線程指的是max_threads-core_threads的線程, 
  14.    * 當(dāng)time_out時間內(nèi)沒有執(zhí)行任務(wù),此線程就會被自動回收 
  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.    * 線程的狀態(tài):有等待、運(yùn)行、停止 
  25.    */ 
  26.   enum class ThreadState { kInit = 0, kWaiting = 1, kRunning = 2, kStop = 3 }; 
  27.  
  28.   /** 
  29.    * 線程的種類標(biāo)識:標(biāo)志該線程是核心線程還是Cache線程,Cache是內(nèi)部為了執(zhí)行更多任務(wù)臨時創(chuàng)建出來的 
  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,有線程種類標(biāo)識和狀態(tài) 
  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_; // 用于為新創(chuàng)建的線程分配ID 
  68.  
  69.   std::atomic<bool> is_shutdown_now_; 
  70.   std::atomic<bool> is_shutdown_; 
  71.   std::atomic<bool> is_available_; 
  72. }; 

線程池的初始化

在構(gòu)造函數(shù)中將各個成員變量都附初值,同時判斷線程池的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

如何開啟線程池功能?

創(chuàng)建核心線程數(shù)個線程,常駐于線程池,等待任務(wù)的執(zhí)行,線程ID由GetNextThreadId()統(tǒng)一分配。

  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

如何關(guān)閉線程?

這里有兩個標(biāo)志位,is_shutdown_now置為true表示立即關(guān)閉線程,is_shutdown置為true則表示先執(zhí)行完隊列里的任務(wù)再關(guān)閉線程池。

  1. // 關(guān)掉線程池,內(nèi)部還沒有執(zhí)行的任務(wù)會繼續(xù)執(zhí)行 
  2. void ShutDown() { 
  3.     ShutDown(false); 
  4.     cout << "shutdown" << endl; 
  5.  
  6. // 執(zhí)行關(guān)掉線程池,內(nèi)部還沒有執(zhí)行的任務(wù)直接取消,不會再執(zhí)行 
  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()函數(shù),默認(rèn)會創(chuàng)建Core線程,也可以選擇創(chuàng)建Cache線程,線程內(nèi)部會有一個死循環(huán),不停的等待任務(wù),有任務(wù)到來時就會執(zhí)行,同時內(nèi)部會判斷是否是Cache線程,如果是Cache線程,timeout時間內(nèi)沒有任務(wù)執(zhí)行就會自動退出循環(huán),線程結(jié)束。

這里還會檢查is_shutdown和is_shutdown_now標(biāo)志,根據(jù)兩個標(biāo)志位是否為true來判斷是否結(jié)束線程。

  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)); 

如何將任務(wù)放入線程池中執(zhí)行?

見如下代碼,將任務(wù)使用std::bind封裝成std::function放入任務(wù)隊列中,任務(wù)較多時內(nèi)部還會判斷是否有空閑線程,如果沒有空閑線程,會自動創(chuàng)建出最多(max_threads-core_threads)個Cache線程用于執(zhí)行任務(wù)。

  1. // 放在線程池中執(zhí)行函數(shù) 
  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)); 

如何獲取當(dāng)前線程池中線程的總個數(shù)?

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

如何獲取當(dāng)前線程池中空閑線程的個數(shù)?

waiting_thread_num值表示空閑線程的個數(shù),該變量在線程循環(huán)內(nèi)部會更新。

  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; 

 

責(zé)任編輯:武曉燕 來源: 程序喵大人
相關(guān)推薦

2023-07-11 08:34:25

參數(shù)流程類型

2024-12-10 00:00:25

2025-02-28 08:46:24

框架微服務(wù)架構(gòu)

2021-10-04 09:29:41

對象池線程池

2024-06-04 07:52:04

2024-08-29 09:18:55

2025-01-09 10:57:54

2024-08-02 09:49:35

Spring流程Tomcat

2024-06-17 11:59:39

2022-08-29 07:48:27

文件數(shù)據(jù)參數(shù)類型

2024-08-12 15:55:51

2021-11-15 11:03:09

接口壓測工具

2023-07-16 22:57:38

代碼場景業(yè)務(wù)

2021-12-14 07:40:07

多線程面試CPU

2023-10-31 09:04:21

CPU調(diào)度Java

2021-12-30 06:59:27

視頻通話網(wǎng)頁

2021-05-14 13:30:17

Mybatis分表插件

2024-07-03 08:36:14

序列化算法設(shè)計模式

2022-06-27 08:00:49

hook工具庫函數(shù)

2023-08-04 08:20:56

DockerfileDocker工具
點贊
收藏

51CTO技術(shù)棧公眾號