C++笔记之一个轻量级的线程池库threadpool
code review!
抄自:https://github.com/lzpong/
文章目录
- C++笔记之一个轻量级的线程池库threadpool
- 1.threadpool.h
- 2.使用:test2.cc
- 3.使用:test1.cc
- 4.代码
1.threadpool.h
2.使用:test2.cc
运行(GIF动图)
3.使用:test1.cc
运行(GIF动图)
4.代码
threadpool.h
#pragma once
#ifndef THREAD_POOL_H
#define THREAD_POOL_H
#include <atomic>
#include <future>
#include <queue>
#include <vector>
// #include <condition_variable>
// #include <thread>
#include <functional>
#include <stdexcept>
namespace std {
// 线程池最大容量,应尽量设小一点
#define THREADPOOL_MAX_NUM 16
// #define THREADPOOL_AUTO_GROW
// 线程池,可以提交变参函数或拉姆达表达式的匿名函数执行,可以获取执行返回值
// 不直接支持类成员函数, 支持类静态成员函数或全局函数,Opteron()函数等
class threadpool {
using Task = function<void()>; // 定义类型
vector<thread> _pool; // 线程池
queue<Task> tasks_queue; // 任务队列
mutex _lock; // 同步
condition_variable _task_cv; // 条件阻塞
atomic<bool> run_flag{true}; // 线程池是否执行
atomic<int> _idlThrNum{0}; // 空闲线程数量
public:
inline threadpool(unsigned short size = 4) { addThread(size); } // 构造函数,创建线程池并指定初始线程数量,默认为4。
inline ~threadpool() { // 析构函数,销毁线程池,等待所有任务执行完毕。
run_flag = false;
_task_cv.notify_all(); // 唤醒所有线程执行
for (thread &thread : _pool) {
// thread.detach();// 让线程“自生自灭”
if (thread.joinable()) {
thread.join(); // 等待任务结束, 前提:线程一定会执行完
}
}
}
public:
// 提交一个任务
// 调用.get()获取返回值会等待任务执行完,获取返回值
// 有两种方法可以实现调用类成员,
// 一种是使用 bind:.commit(std::bind(&Dog::sayHello, &dog));
// 一种是用 mem_fn:.commit(std::mem_fn(&Dog::sayHello), this)
template <class F, class... Args>
auto commit(F &&f, Args &&...args) -> future<decltype(f(args...))> { // 提交一个任务,执行函数f,可以等待任务执行完毕并获取返回值。
if (!run_flag) { // stoped ??
throw runtime_error("commit on ThreadPool is stopped.");
}
using RetType = decltype(f(args...)); // typename std::result_of<F(Args...)>::type, 函数 f 的返回值类型
auto task = make_shared<packaged_task<RetType()>>(bind(forward<F>(f), forward<Args>(args)...)); // 把函数入口及参数,打包(绑定)
future<RetType> future = task->get_future();
// 添加任务到队列
lock_guard<mutex> lock{_lock}; // 对当前块的语句加锁 lock_guard 是 mutex 的 stack 封装类,构造的时候 lock(),析构的时候 unlock()
tasks_queue.emplace([task]() { (*task)(); }); // push(Task{...}) 放到队列后面
#ifdef THREADPOOL_AUTO_GROW
if (_idlThrNum < 1 && _pool.size() < THREADPOOL_MAX_NUM)
addThread(1);
#endif // !THREADPOOL_AUTO_GROW
_task_cv.notify_one(); // 唤醒一个线程执行
return future;
}
// 获取当前空闲线程数量
int idlCount() { return _idlThrNum; }
// 获取线程池中线程的数量。
int thrCount() { return _pool.size(); }
#ifndef THREADPOOL_AUTO_GROW
private:
#endif // !THREADPOOL_AUTO_GROW
// 添加指定数量的线程
void addThread(unsigned short size) { // 添加指定数量的线程到线程池,但不超过预定义的最大线程数量THREADPOOL_MAX_NUM。
for (; _pool.size() < THREADPOOL_MAX_NUM && size > 0; --size) { // 增加线程数量,但不超过 预定义数量 THREADPOOL_MAX_NUM
_pool.emplace_back([this] { // 工作线程函数
while (run_flag) {
Task task; // 获取一个待执行的 task
// unique_lock 相比 lock_guard 的好处是:可以随时 unlock() 和 lock()
unique_lock<mutex> lock{_lock};
_task_cv.wait(lock, [this] { return !run_flag || !tasks_queue.empty(); }); // wait 直到有 task
if (!run_flag && tasks_queue.empty()) {
return;
}
task = move(tasks_queue.front()); // 按先进先出从队列取一个 task
tasks_queue.pop();
_idlThrNum--;
task(); // 执行任务
_idlThrNum++;
}
});
_idlThrNum++;
}
}
};
} // namespace std
#endif // https://github.com/lzpong/
test2.cc
#include "threadpool.h"
#include <chrono>
#include <iostream>
using namespace std;
void myTask(int n) {
cout << "Task " << n << " executed" << endl;
this_thread::sleep_for(chrono::seconds(2));
}
int main() {
std::threadpool pool(4); // 创建一个最多包含4个线程的线程池
// 提交任务给线程池执行
for (int i = 0; i < 20; ++i) {
pool.commit(myTask, i);
}
this_thread::sleep_for(chrono::seconds(10));
return 0;
}
// g++ main.cc -o main -lpthread
test1.cc
#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) { //函数必须是 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(); //调用.get()获取返回值会等待线程执行完,获取返回值
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(); //调用.get()获取返回值会等待线程执行完
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;
}