使用:
ThreadPool threadPool(12); //设定数量
threadPool.queue(myFunction,args1,args2,...); //创建任务
实现:
#include <windows.h>
#include <iostream>
#include <functional>
#include <vector>
#include <queue>
#include <mutex>
#include <condition_variable>
class ThreadPool {
public:
ThreadPool(size_t numThreads) : stop(false) {
for (size_t i = 0; i < numThreads; ++i) {
workers.emplace_back([this] {
while (true) {
std::function<void()> task;
{
std::unique_lock<std::mutex> lock(queueMutex);
condition.wait(lock, [this] { return stop || !tasks.empty(); });
if (stop && tasks.empty()) {
return;
}
task = std::move(tasks.front());
tasks.pop();
}
task();
}
});
}
}
template<typename Function, typename... Args>
void queue(Function&& f, Args&&... args) {
auto task = [f, args...]{ f(args...); };
{
std::unique_lock<std::mutex> lock(queueMutex);
tasks.emplace(std::move(task));
}
condition.notify_one();
}
~ThreadPool() {
{
std::unique_lock<std::mutex> lock(queueMutex);
stop = true;
}
condition.notify_all();
for (std::thread& worker : workers) {
worker.join();
}
}
private:
std::vector<std::thread> workers;
std::queue<std::function<void()>> tasks;
std::mutex queueMutex;
std::condition_variable condition;
bool stop;
};
标签:std,tasks,Windows,lock,stop,C++,task,线程,include
From: https://www.cnblogs.com/tutuleilife/p/17859392.html