在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;
}
請注意,上述示例僅用于演示目的,實際應用中可能需要根據具體需求進行調整和優化。