82 lines
1.7 KiB
C++
82 lines
1.7 KiB
C++
//
|
|
// Created by xtkuang on 2025/5/13.
|
|
//
|
|
|
|
#ifndef CMVR_ES_THREAD_POOL_H
|
|
#define CMVR_ES_THREAD_POOL_H
|
|
|
|
|
|
#include <thread>
|
|
#include <vector>
|
|
#include <functional>
|
|
#include <atomic>
|
|
#include <mutex>
|
|
#include <condition_variable>
|
|
#include <memory>
|
|
#include <chrono>
|
|
#include <future>
|
|
#include <boost/lockfree/queue.hpp>
|
|
#pragma warning(disable:4996)
|
|
#define GLOG_USE_GLOG_EXPORT
|
|
#include <glog/logging.h>
|
|
|
|
class InterruptFlag {
|
|
public:
|
|
void request_stop();
|
|
[[nodiscard]] bool stop_requested() const;
|
|
|
|
private:
|
|
std::atomic<bool> flag_ {false};
|
|
};
|
|
|
|
// 提交任务(带 future 返回)
|
|
class TaskHandle {
|
|
public:
|
|
using TaskFuncType = std::function<void()>;
|
|
using ReturnType = void;
|
|
|
|
TaskHandle(std::shared_ptr<std::promise<ReturnType>> promise)
|
|
: future_(promise->get_future()) {}
|
|
|
|
std::future<ReturnType>& get_future() { return future_; }
|
|
|
|
private:
|
|
std::future<ReturnType> future_;
|
|
};
|
|
|
|
|
|
class ThreadPool {
|
|
public:
|
|
ThreadPool(size_t min_threads, size_t max_threads);
|
|
~ThreadPool();
|
|
|
|
// 提交任务(不带返回值)
|
|
void submit(std::function<void(InterruptFlag&)> task);
|
|
|
|
TaskHandle submit_with_future(std::function<TaskHandle::TaskFuncType()> f);
|
|
|
|
void shutdown();
|
|
|
|
private:
|
|
void worker_loop(size_t id);
|
|
void monitor_loop();
|
|
|
|
boost::lockfree::queue<std::function<void(InterruptFlag&)>*> task_queue_;
|
|
std::atomic<size_t> pending_tasks_;
|
|
|
|
std::vector<std::thread> threads_;
|
|
std::vector<std::unique_ptr<InterruptFlag>> flags_;
|
|
|
|
std::mutex control_mutex_;
|
|
std::condition_variable control_cv_;
|
|
std::atomic<bool> shutdown_requested_ = false;
|
|
|
|
const size_t min_threads_;
|
|
const size_t max_threads_;
|
|
|
|
std::thread monitor_thread_;
|
|
};
|
|
|
|
|
|
#endif //CMVR_ES_THREAD_POOL_H
|