117 lines
3.0 KiB
C++
117 lines
3.0 KiB
C++
#ifndef THREAD_POOL_H
|
|
#define THREAD_POOL_H
|
|
|
|
#include <vector>
|
|
#include <queue>
|
|
#include <memory>
|
|
#include <thread>
|
|
#include <mutex>
|
|
#include <condition_variable>
|
|
#include <future>
|
|
#include <functional>
|
|
#include <stdexcept>
|
|
#include <atomic>
|
|
#include <chrono>
|
|
|
|
#define MAX_THREAD_POOL_SIZE 5
|
|
class ThreadPool {
|
|
public:
|
|
using Task = std::function<void()>;
|
|
|
|
struct TaskWrapper {
|
|
Task task;
|
|
int priority;
|
|
std::chrono::steady_clock::time_point enqueueTime;
|
|
|
|
bool operator<(const TaskWrapper& other) const {
|
|
// 优先级高的先执行,同优先级按入队时间FIFO
|
|
if (priority != other.priority) {
|
|
return priority < other.priority;
|
|
}
|
|
return enqueueTime > other.enqueueTime;
|
|
}
|
|
};
|
|
|
|
explicit ThreadPool(size_t initialThreads = std::thread::hardware_concurrency());
|
|
~ThreadPool();
|
|
|
|
// 提交任务到线程池,返回future
|
|
template<class F, class... Args>
|
|
auto submitTask(int priority, F&& f, Args&&... args)
|
|
-> std::future<typename std::result_of<F(Args...)>::type> {
|
|
using return_type = typename std::result_of<F(Args...)>::type;
|
|
|
|
auto task = std::make_shared< std::packaged_task<return_type()> >(
|
|
std::bind(std::forward<F>(f), std::forward<Args>(args)...)
|
|
);
|
|
|
|
std::future<return_type> res = task->get_future();
|
|
{
|
|
std::unique_lock<std::mutex> lock(mutex);
|
|
|
|
// Don't allow enqueueing after stopping the pool
|
|
if(stop)
|
|
throw std::runtime_error("enqueue on stopped ThreadPool");
|
|
|
|
tasks.emplace(TaskWrapper{[task]() { (*task)(); },priority,std::chrono::steady_clock::now()});
|
|
}
|
|
condition.notify_one();
|
|
return res;
|
|
};
|
|
|
|
|
|
// 调整工作线程数量
|
|
void adjustThreadCount(size_t targetThreadCount);
|
|
|
|
// 获取当前工作线程数
|
|
size_t getThreadCount() const;
|
|
|
|
// 获取任务队列大小
|
|
size_t getTaskCount() const;
|
|
|
|
// 获取正在执行任务的线程数
|
|
size_t getBusyThreadCount() const;
|
|
|
|
// 停止线程池
|
|
void shutdown();
|
|
|
|
// 等待所有任务完成
|
|
void waitForAllTasks();
|
|
|
|
private:
|
|
// 工作线程函数
|
|
void workerThread();
|
|
|
|
// 管理线程函数
|
|
void managerThread();
|
|
|
|
// 添加工作线程
|
|
void addWorker(size_t num = 1);
|
|
|
|
// 移除工作线程
|
|
void removeWorker(size_t num = 1);
|
|
|
|
std::vector<std::thread> workers;
|
|
std::priority_queue<TaskWrapper> tasks;
|
|
std::thread manager;
|
|
|
|
// 同步
|
|
mutable std::mutex mutex;
|
|
std::condition_variable condition;
|
|
std::condition_variable waitCondition;
|
|
|
|
// 状态标志
|
|
std::atomic<bool> stop;
|
|
std::atomic<size_t> busyThreads;
|
|
std::atomic<size_t> totalThreads;
|
|
std::atomic<size_t> pendingStopThreads;
|
|
|
|
// 性能统计
|
|
std::atomic<size_t> completedTasks;
|
|
std::atomic<size_t> totalTasks;
|
|
std::chrono::steady_clock::time_point lastAdjustment;
|
|
};
|
|
|
|
//#include "thread_pool.inl"
|
|
|
|
#endif // THREAD_POOL_H
|