C++ 线程池实现及设计思路详解
以下是一个简单的线程池的 C++ 实现源代码:
#include <iostream>
#include <queue>
#include <thread>
#include <mutex>
#include <condition_variable>
class ThreadPool {
public:
ThreadPool(int numThreads) : stop(false) {
for (int i = 0; i < numThreads; ++i) {
threads.emplace_back([this] {
while (true) {
std::function<void()> task;
{
std::unique_lock<std::mutex> lock(this->queueMutex);
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();
}
});
}
}
template<typename Func, typename... Args>
void enqueue(Func&& func, Args&&... args) {
std::function<void()> task = std::bind(std::forward<Func>(func), std::forward<Args>(args)...);
{
std::unique_lock<std::mutex> lock(queueMutex);
tasks.emplace(task);
}
condition.notify_one();
}
~ThreadPool() {
{
std::unique_lock<std::mutex> lock(queueMutex);
stop = true;
}
condition.notify_all();
for (std::thread& thread : threads) {
thread.join();
}
}
private:
std::vector<std::thread> threads;
std::queue<std::function<void()>> tasks;
std::mutex queueMutex;
std::condition_variable condition;
bool stop;
};
这个线程池的设计思路如下:
-
在构造函数中,创建指定数量的线程,并将线程函数定义为一个 lambda 表达式。每个线程会不断从任务队列中取出任务执行。
-
enqueue()函数用于将任务添加到任务队列中。这里使用了std::function来存储不同类型的任务,std::bind用于绑定函数和参数。 -
使用
std::mutex和std::condition_variable来实现线程的同步和互斥。queueMutex用于对任务队列进行互斥访问,condition用于线程间的同步通信。 -
stop标志用于指示线程池是否停止运行。当stop为 true 且任务队列为空时,线程函数会返回退出。 -
在析构函数中,首先将
stop标志设置为 true,然后通知所有线程退出。最后,等待所有线程结束。
通过使用线程池,可以有效地管理和复用线程资源,避免了频繁创建和销毁线程的开销。任务的执行顺序由线程池内部的调度决定,可以提高程序的并发性能。
原文地址: https://www.cveoy.top/t/topic/qgUU 著作权归作者所有。请勿转载和采集!