基于C++11中threadpool線程池的示例分析

這篇文章給大家分享的是有關(guān)基于C++11中threadpool線程池的示例分析的內(nèi)容。小編覺得挺實用的,因此分享給大家做個參考,一起跟隨小編過來看看吧。

廣昌網(wǎng)站制作公司哪家好,找創(chuàng)新互聯(lián)公司!從網(wǎng)頁設(shè)計、網(wǎng)站建設(shè)、微信開發(fā)、APP開發(fā)、自適應(yīng)網(wǎng)站建設(shè)等網(wǎng)站項目制作,到程序開發(fā),運營維護。創(chuàng)新互聯(lián)公司公司2013年成立到現(xiàn)在10年的時間,我們擁有了豐富的建站經(jīng)驗和運維經(jīng)驗,來保證我們的工作的順利進行。專注于網(wǎng)站建設(shè)就選創(chuàng)新互聯(lián)公司。

C++11 加入了線程庫,從此告別了標準庫不支持并發(fā)的歷史。然而 c++ 對于多線程的支持還是比較低級,稍微高級一點的用法都需要自己去實現(xiàn),譬如線程池、信號量等。線程池(thread pool)這個東西,在面試上多次被問到,一般的回答都是:“管理一個任務(wù)隊列,一個線程隊列,然后每次取一個任務(wù)分配給一個線程去做,循環(huán)往復(fù)。” 貌似沒有問題吧。但是寫起程序來的時候就出問題了。

代碼實現(xiàn)

#pragma once
#ifndef THREAD_POOL_H
#define THREAD_POOL_H

#include <vector>
#include <queue>
#include <thread>
#include <atomic>
#include <condition_variable>
#include <future>
#include <functional>
#include <stdexcept>

namespace std
{
#define MAX_THREAD_NUM 256

//線程池,可以提交變參函數(shù)或拉姆達表達式的匿名函數(shù)執(zhí)行,可以獲取執(zhí)行返回值
//不支持類成員函數(shù), 支持類靜態(tài)成員函數(shù)或全局函數(shù),Opteron()函數(shù)等
class threadpool
{
  using Task = std::function<void()>;
  // 線程池
  std::vector<std::thread> pool;
  // 任務(wù)隊列
  std::queue<Task> tasks;
  // 同步
  std::mutex m_lock;
  // 條件阻塞
  std::condition_variable cv_task;
  // 是否關(guān)閉提交
  std::atomic<bool> stoped;
  //空閑線程數(shù)量
  std::atomic<int> idlThrNum;

public:
  inline threadpool(unsigned short size = 4) :stoped{ false }
  {
    idlThrNum = size < 1 ? 1 : size;
    for (size = 0; size < idlThrNum; ++size)
    {  //初始化線程數(shù)量
      pool.emplace_back(
        [this]
        { // 工作線程函數(shù)
          while(!this->stoped)
          {
            std::function<void()> task;
            {  // 獲取一個待執(zhí)行的 task
              std::unique_lock<std::mutex> lock{ this->m_lock };// unique_lock 相比 lock_guard 的好處是:可以隨時 unlock() 和 lock()
              this->cv_task.wait(lock,
                [this] {
                  return this->stoped.load() || !this->tasks.empty();
                }
              ); // wait 直到有 task
              if (this->stoped && this->tasks.empty())
                return;
              task = std::move(this->tasks.front()); // 取一個 task
              this->tasks.pop();
            }
            idlThrNum--;
            task();
            idlThrNum++;
          }
        }
      );
    }
  }
  inline ~threadpool()
  {
    stoped.store(true);
    cv_task.notify_all(); // 喚醒所有線程執(zhí)行
    for (std::thread& thread : pool) {
      //thread.detach(); // 讓線程“自生自滅”
      if(thread.joinable())
        thread.join(); // 等待任務(wù)結(jié)束, 前提:線程一定會執(zhí)行完
    }
  }

public:
  // 提交一個任務(wù)
  // 調(diào)用.get()獲取返回值會等待任務(wù)執(zhí)行完,獲取返回值
  // 有兩種方法可以實現(xiàn)調(diào)用類成員,
  // 一種是使用  bind: .commit(std::bind(&Dog::sayHello, &dog));
  // 一種是用 mem_fn: .commit(std::mem_fn(&Dog::sayHello), &dog)
  template<class F, class... Args>
  auto commit(F&& f, Args&&... args) ->std::future<decltype(f(args...))>
  {
    if (stoped.load())  // stop == true ??
      throw std::runtime_error("commit on ThreadPool is stopped.");

    using RetType = decltype(f(args...)); // typename std::result_of<F(Args...)>::type, 函數(shù) f 的返回值類型
    auto task = std::make_shared<std::packaged_task<RetType()> >(
      std::bind(std::forward<F>(f), std::forward<Args>(args)...)
      );  // wtf !
    std::future<RetType> future = task->get_future();
    {  // 添加任務(wù)到隊列
      std::lock_guard<std::mutex> lock{ m_lock };//對當前塊的語句加鎖 lock_guard 是 mutex 的 stack 封裝類,構(gòu)造的時候 lock(),析構(gòu)的時候 unlock()
      tasks.emplace(
        [task]()
        { // push(Task{...})
          (*task)();
        }
      );
    }
    cv_task.notify_one(); // 喚醒一個線程執(zhí)行

    return future;
  }

  //空閑線程數(shù)量
  int idlCount() { return idlThrNum; }

};

}

#endif

代碼不多吧,上百行代碼就完成了 線程池, 并且, 看看 commit, 哈, 不是固定參數(shù)的, 無參數(shù)數(shù)量限制! 這得益于可變參數(shù)模板.

怎么使用?

看下面代碼(展開查看)

#include "threadpool.h"
#include <iostream>

void fun1(int slp)
{
  printf(" hello, fun1 ! %d\n" ,std::this_thread::get_id());
  if (slp>0) {
    printf(" ======= fun1 sleep %d ========= %d\n",slp, std::this_thread::get_id());
    std::this_thread::sleep_for(std::chrono::milliseconds(slp));
  }
}

struct gfun {
  int operator()(int n) {
    printf("%d hello, gfun ! %d\n" ,n, std::this_thread::get_id() );
    return 42;
  }
};

class A { 
public:
  static int Afun(int n = 0) {  //函數(shù)必須是 static 的才能直接使用線程池
    std::cout << n << " hello, Afun ! " << std::this_thread::get_id() << std::endl;
    return n;
  }

  static std::string Bfun(int n, std::string str, char c) {
    std::cout << n << " hello, Bfun ! "<< str.c_str() <<" " << (int)c <<" " << std::this_thread::get_id() << std::endl;
    return str;
  }
};

int main()
  try {
    std::threadpool executor{ 50 };
    A a;
    std::future<void> ff = executor.commit(fun1,0);
    std::future<int> fg = executor.commit(gfun{},0);
    std::future<int> gg = executor.commit(a.Afun, 9999); //IDE提示錯誤,但可以編譯運行
    std::future<std::string> gh = executor.commit(A::Bfun, 9998,"mult args", 123);
    std::future<std::string> fh = executor.commit([]()->std::string { std::cout << "hello, fh ! " << std::this_thread::get_id() << std::endl; return "hello,fh ret !"; });

    std::cout << " ======= sleep ========= " << std::this_thread::get_id() << std::endl;
    std::this_thread::sleep_for(std::chrono::microseconds(900));

    for (int i = 0; i < 50; i++) {
      executor.commit(fun1,i*100 );
    }
    std::cout << " ======= commit all ========= " << std::this_thread::get_id()<< " idlsize="<<executor.idlCount() << std::endl;

    std::cout << " ======= sleep ========= " << std::this_thread::get_id() << std::endl;
    std::this_thread::sleep_for(std::chrono::seconds(3));

    ff.get(); //調(diào)用.get()獲取返回值會等待線程執(zhí)行完,獲取返回值
    std::cout << fg.get() << " " << fh.get().c_str()<< " " << std::this_thread::get_id() << std::endl;

    std::cout << " ======= sleep ========= " << std::this_thread::get_id() << std::endl;
    std::this_thread::sleep_for(std::chrono::seconds(3));

    std::cout << " ======= fun1,55 ========= " << std::this_thread::get_id() << std::endl;
    executor.commit(fun1,55).get();  //調(diào)用.get()獲取返回值會等待線程執(zhí)行完

    std::cout << "end... " << std::this_thread::get_id() << std::endl;


    std::threadpool pool(4);
    std::vector< std::future<int> > results;

    for (int i = 0; i < 8; ++i) {
      results.emplace_back(
        pool.commit([i] {
          std::cout << "hello " << i << std::endl;
          std::this_thread::sleep_for(std::chrono::seconds(1));
          std::cout << "world " << i << std::endl;
          return i*i;
        })
      );
    }
    std::cout << " ======= commit all2 ========= " << std::this_thread::get_id() << std::endl;

    for (auto && result : results)
      std::cout << result.get() << ' ';
    std::cout << std::endl;
    return 0;
  }
catch (std::exception& e) {
  std::cout << "some unhappy happened... " << std::this_thread::get_id() << e.what() << std::endl;
}

為了避嫌,先進行一下版權(quán)說明:代碼是 me “寫”的,但是思路來自 Internet, 特別是這個線程池實現(xiàn)(基本 copy 了這個實現(xiàn),加上這位同學的實現(xiàn)和解釋,好東西值得 copy ! 然后綜合更改了下,更加簡潔)。

實現(xiàn)原理

接著前面的廢話說?!肮芾硪粋€任務(wù)隊列,一個線程隊列,然后每次取一個任務(wù)分配給一個線程去做,循環(huán)往復(fù)?!?這個思路有神馬問題?線程池一般要復(fù)用線程,所以如果是取一個 task 分配給某一個 thread,執(zhí)行完之后再重新分配,在語言層面基本都是不支持的:一般語言的 thread 都是執(zhí)行一個固定的 task 函數(shù),執(zhí)行完畢線程也就結(jié)束了(至少 c++ 是這樣)。so 要如何實現(xiàn) task 和 thread 的分配呢?

讓每一個 thread 都去執(zhí)行調(diào)度函數(shù):循環(huán)獲取一個 task,然后執(zhí)行之。

idea 是不是很贊!保證了 thread 函數(shù)的唯一性,而且復(fù)用線程執(zhí)行 task 。

即使理解了 idea,代碼還是需要詳細解釋一下的。

1、一個線程 pool,一個任務(wù)隊列 queue ,應(yīng)該沒有意見;
2、任務(wù)隊列是典型的生產(chǎn)者-消費者模型,本模型至少需要兩個工具:一個 mutex + 一個條件變量,或是一個 mutex + 一個信號量。mutex 實際上就是鎖,保證任務(wù)的添加和移除(獲取)的互斥性,一個條件變量是保證獲取 task 的同步性:一個 empty 的隊列,線程應(yīng)該等待(阻塞);
3、atomic<bool> 本身是原子類型,從名字上就懂:它們的操作 load()/store() 是原子操作,所以不需要再加 mutex。

c++語言細節(jié)

即使懂原理也不代表能寫出程序,上面用了眾多c++11的“奇技淫巧”,下面簡單描述之。

  1. using Task = function<void()> 是類型別名,簡化了 typedef 的用法。function<void()> 可以認為是一個函數(shù)類型,接受任意原型是 void() 的函數(shù),或是函數(shù)對象,或是匿名函數(shù)。void() 意思是不帶參數(shù),沒有返回值。

  2. pool.emplace_back([this]{...}) 和 pool.push_back([this]{...}) 功能一樣,只不過前者性能會更好;

  3. pool.emplace_back([this]{...}) 是構(gòu)造了一個線程對象,執(zhí)行函數(shù)是拉姆達匿名函數(shù) ;

  4. 所有對象的初始化方式均采用了 {},而不再使用 () 方式,因為風格不夠一致且容易出錯;

  5. 匿名函數(shù): [this]{...} 不多說。[] 是捕捉器,this 是引用域外的變量 this指針, 內(nèi)部使用死循環(huán), 由cv_task.wait(lock,[this]{...}) 來阻塞線程;

  6. delctype(expr) 用來推斷 expr 的類型,和 auto 是類似的,相當于類型占位符,占據(jù)一個類型的位置;auto f(A a, B b) -> decltype(a+b) 是一種用法,不能寫作 decltype(a+b) f(A a, B b),為啥?! c++ 就是這么規(guī)定的!

  7. commit 方法是不是略奇葩!可以帶任意多的參數(shù),第一個參數(shù)是 f,后面依次是函數(shù) f 的參數(shù)!(注意:參數(shù)要傳struct/class的話,建議用pointer,小心變量的作用域) 可變參數(shù)模板是 c++11 的一大亮點,夠亮!至于為什么是 Arg... 和 arg... ,因為規(guī)定就是這么用的!

  8. commit 直接使用只能調(diào)用stdcall函數(shù),但有兩種方法可以實現(xiàn)調(diào)用類成員,一種是使用   bind: .commit(std::bind(&Dog::sayHello, &dog)); 一種是用 mem_fn: .commit(std::mem_fn(&Dog::sayHello), &dog);

  9. make_shared 用來構(gòu)造 shared_ptr 智能指針。用法大體是 shared_ptr<int> p = make_shared<int>(4) 然后 *p == 4 。智能指針的好處就是, 自動 delete !

  10. bind 函數(shù),接受函數(shù) f 和部分參數(shù),返回currying后的匿名函數(shù),譬如 bind(add, 4) 可以實現(xiàn)類似 add4 的函數(shù)!

  11. forward() 函數(shù),類似于 move() 函數(shù),后者是將參數(shù)右值化,前者是... 腫么說呢?大概意思就是:不改變最初傳入的類型的引用類型(左值還是左值,右值還是右值);

  12. packaged_task 就是任務(wù)函數(shù)的封裝類,通過 get_future 獲取 future , 然后通過 future 可以獲取函數(shù)的返回值(future.get());packaged_task 本身可以像函數(shù)一樣調(diào)用 () ;

  13. queue 是隊列類, front() 獲取頭部元素, pop() 移除頭部元素;back() 獲取尾部元素,push() 尾部添加元素;

  14. lock_guard 是 mutex 的 stack 封裝類,構(gòu)造的時候 lock(),析構(gòu)的時候 unlock(),是 c++ RAII 的 idea;

  15. condition_variable cv; 條件變量, 需要配合 unique_lock 使用;unique_lock 相比 lock_guard 的好處是:可以隨時 unlock() 和 lock()。 cv.wait() 之前需要持有 mutex,wait 本身會 unlock() mutex,如果條件滿足則會重新持有 mutex。

  16. 最后線程池析構(gòu)的時候,join() 可以等待任務(wù)都執(zhí)行完在結(jié)束,很安全!

感謝各位的閱讀!關(guān)于“基于C++11中threadpool線程池的示例分析”這篇文章就分享到這里了,希望以上內(nèi)容可以對大家有一定的幫助,讓大家可以學到更多知識,如果覺得文章不錯,可以把它分享出去讓更多的人看到吧!

網(wǎng)頁題目:基于C++11中threadpool線程池的示例分析
當前地址:http://bm7419.com/article20/jjdhjo.html

成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供網(wǎng)站改版Google、品牌網(wǎng)站設(shè)計、網(wǎng)站內(nèi)鏈、網(wǎng)頁設(shè)計公司、網(wǎng)站導(dǎo)航

廣告

聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時需注明來源: 創(chuàng)新互聯(lián)

成都app開發(fā)公司