1. 程式人生 > 程式設計 >C++實現執行緒池的簡單方法示例

C++實現執行緒池的簡單方法示例

最近自己寫了一個執行緒池。

總的來說,執行緒池就是有一個任務佇列,一個執行緒佇列,執行緒佇列不斷地去取任務佇列中的任務來執行,當任務佇列中為空時,執行緒阻塞等待新的任務新增過來。

我是用queue來存放任務,vector存放thread*,然後用condition_variable 來設定執行緒阻塞和喚醒。

下面直接上程式碼吧。

執行緒池類標頭檔案Thread_Pool.h

/********************************************
   執行緒池標頭檔案

  Author:十面埋伏但莫慌
  Time:2020/05/03

*********************************************/
#pragma once
#ifndef _THREAD_POOL_H_
#define _THREAD_POOL_H_
#include<thread>
#include<queue>
#include<mutex>
#include<atomic>
#include<vector>
#include<condition_variable>

typedef std::function<void()> Func;//定義執行緒執行函式型別,方便後面編碼使用。
//任務類
class Task {
public:
 Task() {}
 ~Task() {}
 int push(Func func);//新增任務;
 int getTaskNum();//獲得當前佇列中的任務數;
 Func pop();//取出待執行的任務;
public:
 std::mutex mx;//鎖;
private:
 
 std::queue<Func> tasks;//任務佇列
};
//執行緒池類
class Thread_Pool {
public:
 Thread_Pool() :IsStart(false) {}
 ~Thread_Pool();
 int addTasks(Func tasks);//新增任務;
 void start();//開啟執行緒池;
 void stop();//關閉執行緒池;
 void run();//執行緒工作函式;
 int getTaskNum();//獲得當前佇列中的任務數;
private:
 static const int maxThreadNum = 3;//最大執行緒數為3;

 std::condition_variable cond;//條件量;
 std::vector<std::thread*> threads;//執行緒向量;
 std::atomic<bool> IsStart;//原子變數,判斷執行緒池是否執行;
 Task tasks;//任務變數;
};
#endif

然後是執行緒池類成員函式定義檔案Thread_Pool.cpp

/********************************************
   執行緒池CPP檔案

  Author:十面埋伏但莫慌
  Time:2020/05/03

*********************************************/
#include"Thread_Pool.h"
#include<iostream>
int Task::push(Func func) {
 std::unique_lock<std::mutex> lock(mx);
 try {
  tasks.emplace(func);
 }
 catch (std::exception e)
 {
  throw e;
  return -1;
 }
 return 0;
}
int Task::getTaskNum()
{
 return tasks.size();
}
Func Task::pop() {
 std::unique_lock<std::mutex> lock(mx);
 Func temp;
 if (tasks.empty())
  return temp;
 else
 {
  temp = tasks.front();
  tasks.pop();
  return temp;
 }
}
int Thread_Pool::addTasks(Func func)
{
 
 int ret = tasks.push(func);
 cond.notify_one();
 return ret;
}
void Thread_Pool::start() {
 if (!IsStart) {
  IsStart = true;
  for (int i = 0; i < maxThreadNum; i++)
  {
   threads.emplace_back(new std::thread(std::bind(&Thread_Pool::run,this)));   
  }
  
 }
}
void Thread_Pool::run()
{
 while (IsStart)
 {
  Func f;
  if (tasks.getTaskNum() == 0 && IsStart)
  {
   std::unique_lock<std::mutex> lock(tasks.mx);
   cond.wait(lock);
  }
  if (tasks.getTaskNum() != 0 && IsStart)
  {
   f = tasks.pop();
   if(f)
    f();
  }

 }
}
int Thread_Pool::getTaskNum() {
 return tasks.getTaskNum();
}
void Thread_Pool::stop() {

  IsStart = false;
  cond.notify_all();
  for (auto T : threads) {
   std::cout << "執行緒 " << T->get_id() << " 已停止。" << std::endl;
   T->join();
   if (T != nullptr)
   {
    delete T;
    T = nullptr;
   }
  }
 std::cout << "所有執行緒已停止。" << std::endl;
}
Thread_Pool::~Thread_Pool() {
 if (IsStart)
 {
  stop();
 }
}

最後是測試用的main.cpp

#include<iostream>
#include"Thread_Pool.h"
using namespace std;
void string_out_one() {
 cout << "One!" << endl;
}
void string_out_two() {
 cout << "Two!" << endl;
}
void string_out_three() {
 cout << "Three!" << endl;
}
int main() {
 {
  Thread_Pool Pool;
  try {
   Pool.start();
  }
  catch (std::exception e)
  {
   throw e;
   cout << "執行緒池建立失敗。" << endl;
  }
  for (int i = 0; i < 50000 ;)
  {  
   if (Pool.getTaskNum() < 1000) {
    Pool.addTasks(string_out_one);
    Pool.addTasks(string_out_two);
    Pool.addTasks(string_out_three);
    std::cout << i++ << std::endl;
   }
  }
  getchar();
 }
 getchar();
 return 0;
}

執行的效果如下:

C++實現執行緒池的簡單方法示例

執行緒喚醒和阻塞的邏輯就是線上程工作函式run函式中,判斷佇列是否為空,若為空則設定鎖並呼叫condition變數的wait函式,釋放這個執行緒中的鎖並阻塞執行緒,等待任務佇列中新的任務新增進來後,

condition變數通過notify_one()隨機喚醒一個在wait的執行緒,取出佇列中的任務執行。

寫這個執行緒池的過程中碰到的最主要需要注意的就是鎖的使用,在對佇列的寫和釋放時要注意加鎖,在需要阻塞執行緒時,要注意通過{}設定鎖的範圍。

IsStart是原子的,所以在寫這個變數的時候沒有另外加鎖。

目前我覺得這個執行緒池的缺陷就是可執行函式的型別被寫死了,有嘗試對Task類使用模板類,但是在Thread_Pool中還是要指明Task模板類的型別引數,要是有大神指點下就好了- -。

就先記錄這麼多,感覺這個執行緒池的還是有很多可以改進的地方的,也歡迎大家指出不足。

到此這篇關於C++實現執行緒池的簡單方法的文章就介紹到這了,更多相關C++實現執行緒池內容請搜尋我們以前的文章或繼續瀏覽下面的相關文章希望大家以後多多支援我們!