线程池Demo如下,可处理多个单一功能函数。
Thread_Pool.h
#ifndef Thread_Pool_h__
#define Thread_Pool_h__
#include<thread>
#include<queue>
#include<mutex>
#include<atomic>
#include<vector>
#include<condition_variable>
#include <functional>
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_h__
Thread_Pool.cpp
#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();
}
}
使用
void print(int i){std::cout<< i << std::endl}
Thread_Pool Pool;
try {}
catch (std::exception e)
{
throw e;
std::cout << "线程池创建失败。" << std::endl;
}
for (int i = 0; i < 10000; i++)
{
if (Pool.getTaskNum() < 1000)
{
//这里绑定参见bind绑定函数
Pool.addTasks(std::bind(print, this, i));
}
}