cpp-mcp/include/mcp_thread_pool.h

117 lines
3.0 KiB
C
Raw Normal View History

2025-03-12 02:58:30 +08:00
/**
* @file mcp_thread_pool.h
* @brief 线
*/
#ifndef MCP_THREAD_POOL_H
#define MCP_THREAD_POOL_H
#include <vector>
#include <queue>
#include <thread>
#include <mutex>
#include <condition_variable>
#include <functional>
#include <future>
#include <atomic>
namespace mcp {
class thread_pool {
public:
/**
* @brief
* @param num_threads 线线
*/
explicit thread_pool(size_t num_threads = std::thread::hardware_concurrency()) : stop_(false) {
for (size_t i = 0; i < num_threads; ++i) {
workers_.emplace_back([this] {
while (true) {
std::function<void()> task;
{
std::unique_lock<std::mutex> lock(queue_mutex_);
condition_.wait(lock, [this] {
return stop_ || !tasks_.empty();
});
if (stop_ && tasks_.empty()) {
return;
}
task = std::move(tasks_.front());
tasks_.pop();
}
task();
}
});
}
}
/**
* @brief
*/
~thread_pool() {
{
std::unique_lock<std::mutex> lock(queue_mutex_);
stop_ = true;
}
condition_.notify_all();
for (std::thread& worker : workers_) {
if (worker.joinable()) {
worker.join();
}
}
}
/**
* @brief 线
* @param f
* @param args
* @return future
*/
template<class F, class... Args>
auto enqueue(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> result = task->get_future();
{
std::unique_lock<std::mutex> lock(queue_mutex_);
if (stop_) {
throw std::runtime_error("线程池已停止,无法添加任务");
}
tasks_.emplace([task]() { (*task)(); });
}
condition_.notify_one();
return result;
}
private:
// 工作线程
std::vector<std::thread> workers_;
// 任务队列
std::queue<std::function<void()>> tasks_;
// 互斥锁和条件变量
std::mutex queue_mutex_;
std::condition_variable condition_;
// 停止标志
std::atomic<bool> stop_;
};
} // namespace mcp
#endif // MCP_THREAD_POOL_H