cpp-mcp/include/mcp_thread_pool.h

118 lines
3.0 KiB
C
Raw Normal View History

2025-03-12 02:58:30 +08:00
/**
* @file mcp_thread_pool.h
2025-04-01 14:47:30 +08:00
* @brief Simple thread pool implementation
2025-03-12 02:58:30 +08:00
*/
#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>
2025-03-13 21:46:49 +08:00
#include <type_traits>
2025-03-12 02:58:30 +08:00
namespace mcp {
class thread_pool {
public:
/**
2025-04-01 14:47:30 +08:00
* @brief Constructor
* @param num_threads Number of threads in the thread pool
2025-03-12 02:58:30 +08:00
*/
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();
}
});
}
}
/**
2025-04-01 14:47:30 +08:00
* @brief Destructor
2025-03-12 02:58:30 +08:00
*/
~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();
}
}
}
/**
2025-04-01 14:47:30 +08:00
* @brief Submit task to thread pool
* @param f Task function
* @param args Task parameters
* @return Task future
2025-03-12 02:58:30 +08:00
*/
template<class F, class... Args>
2025-03-13 21:46:49 +08:00
auto enqueue(F&& f, Args&&... args) -> std::future<typename std::invoke_result<F, Args...>::type> {
using return_type = typename std::invoke_result<F, Args...>::type;
2025-03-12 02:58:30 +08:00
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_) {
2025-04-01 14:47:30 +08:00
throw std::runtime_error("Thread pool stopped, cannot add task");
2025-03-12 02:58:30 +08:00
}
tasks_.emplace([task]() { (*task)(); });
}
condition_.notify_one();
return result;
}
private:
2025-04-01 14:47:30 +08:00
// Worker threads
2025-03-12 02:58:30 +08:00
std::vector<std::thread> workers_;
2025-04-01 14:47:30 +08:00
// Task queue
2025-03-12 02:58:30 +08:00
std::queue<std::function<void()>> tasks_;
2025-04-01 14:47:30 +08:00
// Mutex and condition variable
2025-03-12 02:58:30 +08:00
std::mutex queue_mutex_;
std::condition_variable condition_;
2025-04-01 14:47:30 +08:00
// Stop flag
2025-03-12 02:58:30 +08:00
std::atomic<bool> stop_;
};
} // namespace mcp
#endif // MCP_THREAD_POOL_H