写一个线程池,能够根据任务数,增加或者减少线程,用c++模板编程
时间: 2023-02-18 11:13:51 浏览: 61
实现:
我可以为您提供一个简单的C++模板线程池的实现,它可以根据任务数量增加或减少线程。它还可以设置最大线程数量,以防止系统资源耗尽。它的实现如下:
template<typename T>
class ThreadPool {
public:
ThreadPool(size_t size) : maxSize(size) {
threads.reserve(size);
}
~ThreadPool() {
stop();
}
void start() {
running = true;
for (size_t i = 0; i < maxSize; ++i) {
threads.emplace_back([this] {
while (running) {
T task;
{
std::unique_lock<std::mutex> lock(mtx);
cv.wait(lock, [this] { return !tasks.empty() || !running; });
if (!running)
break;
task = std::move(tasks.front());
tasks.pop();
}
task();
}
});
}
}
void stop() {
{
std::unique_lock<std::mutex> lock(mtx);
running = false;
}
cv.notify_all();
for (auto& thread : threads) {
thread.join();
}
}
template<typename F>
void enqueue(F&& f) {
{
std::unique_lock<std::mutex> lock(mtx);
tasks.emplace(std::forward<F>(f));
}
cv.notify_one();
}
private:
std::vector<std::thread> threads;
std::queue<T> tasks;
std::mutex mtx;
std::condition_variable cv;
size_t maxSize;
bool running = false;
};