C++线程池
线程池
这是一个基于C++11的线程池
线程池简述
1.是什么
线程池是一种并发编程的设计模式和资源管理技术。它的核心思想是预先创建好一定数量的线程,放入一个“池子”中管理。当有任务需要执行时,不是每次都去创建一个新线程,而是从池子中取出一个空闲线程来执行任务。任务执行完毕后,线程并不销毁,而是返回池中等待执行下一个任务。
简单来说,线程池管理着一组可重用的工作线程(Worker Threads),它们从一个共享的任务队列(Task Queue)中获取任务并执行。
2.解决的问题
首先,线程池的出现,毫无疑问,减少我们以往每次来一个异步任务,都创建->释放一个线程的现状,我们只需要事先创建一个线程池,就可以一直使用线程池中的线程来完成任务,这大大的减少了起线程操作的次数,从而减少了费时费资源操作的次数。
代码实现
ThreadPool.h
#pragma once
#include<vector>
#include<queue>
#include<thread>
#include<functional>
#include<condition_variable>
namespace ll {
class ThreadPool {
public:
ThreadPool(int threadNum = 5) :stopFlag(false) {
for (int i = 0; i < threadNum; i++) {
threads.emplace_back([this]() {
while (1) {
std::unique_lock<std::mutex>lock(mtx);
cond.wait(lock, [this]() {
return !tasks.empty() || stopFlag;
});
if (tasks.empty() && stopFlag)return;//注意是&&,队列为空和stopFlag为真时,我们才结束此线程
std::function<void()>task(std::move(tasks.front()));//移动语义,移动资源
tasks.pop();
lock.unlock();
{
std::unique_lock<std::mutex>lock(printMtx);
task();
}
}
});
}
}
~ThreadPool() {
{
std::unique_lock<std::mutex>lock(mtx);
stopFlag = true;
}
cond.notify_all();
for (auto& it : threads) {
it.join();
}
}
template<class F, class...Args>//可变参数模板
void enqueue(F&& f, Args&&...args) {
std::function<void()>task = std::bind(std::forward<F>(f), std::forward<Args>(args)...);//先完美转发,在参数包展开
{
std::unique_lock<std::mutex>lock(mtx);
tasks.emplace(std::move(task));
}
cond.notify_one();
}
private:
std::mutex mtx;
std::mutex printMtx;
std::condition_variable cond;
std::vector<std::thread>threads;
std::queue<std::function<void()>>tasks;
bool stopFlag;//线程池析构时将stopFlag=true;
};
}
main.cpp
#include<iostream>
#include"../header/ThreadPool.h"
int main() {
ll::ThreadPool threadPool(3);
for (int i = 1; i <= 10; i++) {
threadPool.enqueue([=]() {
std::cout << "完成第" << i << "个任务" << std::endl;
std::this_thread::sleep_for(std::chrono::seconds(1));
});
}
return 0;
}
上述代码涉及到的C++知识点如下:


浙公网安备 33010602011771号