在C++中使用线程池可以通过多种方式实现,以下是一些常见的方法:
<thread>
和 <future>
头文件#include <iostream>
#include <vector>
#include <thread>
#include <future>
#include <queue>
#include <functional>
#include <mutex>
#include <condition_variable>
class ThreadPool {
public:
ThreadPool(size_t threads);
~ThreadPool();
template<class F, class... Args>
auto enqueue(F&& f, Args&&... args) -> std::future<typename std::result_of<F(Args...)>::type>;
private:
// ...(省略部分代码,与上面的代码相同)...
};
// ...(省略构造函数、析构函数和部分成员函数的实现,与上面的代码相同)...
template<class F, class... Args>
auto ThreadPool::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> res = task->get_future();
{
std::unique_lock<std::mutex> lock(m);
if (stop)
throw std::runtime_error("enqueue on stopped ThreadPool");
tasks.emplace([task]() { (*task)(); });
}
condition.notify_one();
return res;
}
int main() {
ThreadPool pool(4);
auto result1 = pool.enqueue([](int a, int b) { return a + b; }, 2, 3);
auto result2 = pool.enqueue([](int a) { return a * a; }, 5);
std::cout << "Result 1: " << result1.get() << std::endl;
std::cout << "Result 2: " << result2.get() << std::endl;
return 0;
}
Boost.Asio 是一个广泛使用的 C++ 库,它提供了异步 I/O 和线程池等功能。要使用 Boost.Asio 创建线程池,你需要安装 Boost 库并包含相应的头文件。
#include <iostream>
#include <boost/asio.hpp>
#include <boost/bind.hpp>
#include <boost/thread.hpp>
class ThreadPool {
public:
ThreadPool(size_t threads);
~ThreadPool();
void enqueue(boost::function<void()> task);
private:
boost::asio::io_service io_service_;
std::vector<boost::thread> threads_;
std::queue<boost::function<void()>> tasks_;
boost::mutex mutex_;
boost::condition_variable condition_;
bool stop_;
};
// ...(省略构造函数、析构函数和部分成员函数的实现,与上面的代码相同)...
void ThreadPool::enqueue(boost::function<void()> task) {
{
boost::unique_lock<boost::mutex> lock(mutex_);
if (stop_)
throw std::runtime_error("enqueue on stopped ThreadPool");
tasks_.push(move(task));
}
condition_.notify_one();
if (threads_.size() == 1) {
threads_[0] = boost::thread([this]() { io_service_.run(); });
}
}
int main() {
ThreadPool pool(4);
pool.enqueue([](int a, int b) { std::cout << a + b << std::endl; }, 2, 3);
pool.enqueue([](int a) { std::cout << a * a << std::endl; }, 5);
boost::this_thread::sleep_for(boost::chrono::seconds(1));
return 0;
}
请注意,上述示例仅用于演示目的,实际应用中可能需要根据具体需求进行调整和优化。