线程池通过预先创建线程并复用避免频繁开销,核心由线程数组、任务队列、互斥锁、条件变量和运行控制开关组成;构造时启动指定数量线程等待任务,析构时设置停止标志并唤醒所有线程以安全退出;任务通过enqueue方法添加,使用模板支持任意可调用对象,并通过条件变量通知空闲线程执行任务,提升并发性能。

实现一个简单的C++线程池,核心思路是预先创建一组线程并让它们等待任务。当有新任务提交时,线程池从队列中取出任务并分配给空闲线程执行。这种方式避免了频繁创建和销毁线程的开销,提升程序性能。
一个基础的线程池通常包含以下几个部分:
#include <vector>
#include <queue>
#include <thread>
#include <functional>
#include <mutex>
#include <condition_variable>
class ThreadPool {
public:
explicit ThreadPool(size_t numThreads);
~ThreadPool();
template<class F>
void enqueue(F&& f);
private:
std::vector<std::thread> workers; // 工作线程
std::queue<std::function<void()>> tasks; // 任务队列
std::mutex queue_mutex; // 保护队列
std::condition_variable condition; // 唤醒线程
bool stop; // 是否停止
};
// 构造函数:启动指定数量的线程
ThreadPool::ThreadPool(size_t numThreads) : stop(false) {
for (size_t i = 0; i < numThreads; ++i) {
workers.emplace_back([this] {
for (;;) {
// 等待任务
std::function<void()> task;
{
std::unique_lock<std::mutex> lock(this->queue_mutex);
this->condition.wait(lock, [this] {
return this->stop || !this->tasks.empty();
});
if (this->stop && this->tasks.empty())
return;
task = std::move(this->tasks.front());
this->tasks.pop();
}
task(); // 执行任务
}
});
}
}
// 析构函数:清理资源
ThreadPool::~ThreadPool() {
{
std::unique_lock<std::mutex> lock(queue_mutex);
stop = true;
}
condition.notify_all(); // 唤醒所有线程
for (std::thread &worker : workers)
worker.join(); // 等待线程结束
}
// 添加任务
template<class F>
void ThreadPool::enqueue(F&& f) {
{
std::unique_lock<std::mutex> lock(queue_mutex);
tasks.emplace(std::forward<F>(f));
}
condition.notify_one(); // 通知一个线程
}
下面是一个简单的使用例子,展示如何创建线程池并提交多个任务:
// main.cpp
#include "threadpool.h"
#include <iostream>
#include <chrono>
int main() {
// 创建一个包含4个线程的线程池
ThreadPool pool(4);
// 提交10个任务
for (int i = 0; i < 10; ++i) {
pool.enqueue([i] {
std::cout << "任务 " << i << " 正在由线程 "
<< std::this_thread::get_id() << " 执行\n";
std::this_thread::sleep_for(std::chrono::milliseconds(100));
});
}
// 主函数退出前,析构函数会自动等待所有线程完成
std::this_thread::sleep_for(std::chrono::seconds(2));
return 0;
}
这个简单线程池的关键设计包括:
立即学习“C++免费学习笔记(深入)”;
基本上就这些。这个线程池适合学习和小型项目使用。实际生产环境可能需要支持任务优先级、动态扩容、返回值获取(配合 std::future)等功能,但基本原理一致。
以上就是c++++如何实现一个简单的线程池 _c++线程池创建与使用方法的详细内容,更多请关注php中文网其它相关文章!
c++怎么学习?c++怎么入门?c++在哪学?c++怎么学才快?不用担心,这里为大家提供了c++速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号