使用 std::thread 实现一个线程池,即一个异步任务队列。
- User
使用 std::thread 实现一个线程池,即一个异步任务队列。
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
使用 std::thread 实现一个线程池,即一个异步任务队列。
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
std::thread)下面是一个简单但完整的线程池实现,它使用 std::thread 管理线程,并维护一个任务队列来实现异步任务执行。
#include <iostream>
#include <vector>
#include <queue>
#include <thread>
#include <mutex>
#include <condition_variable>
#include <functional>
#include <future>
#include <atomic>
#include <memory>
class ThreadPool {
public:
// 构造函数,指定线程数量
explicit ThreadPool(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();
}
});
}
}
// 添加任务到队列
template<class F, class... Args>
auto enqueue(F&& f, Args&&... args) -> std::future<typename std::invoke_result_t<F, Args...>> {
using return_type = typename std::invoke_result_t<F, Args...>;
// 创建任务包装器
auto task = std::make_shared<std::packaged_task<return_type()>>(
std::bind(std::forward<F>(f), std::forward<Args>(args)...)
);
// 获取任务的future
std::future<return_type> res = task->get_future();
{
std::unique_lock<std::mutex> lock(queue_mutex);
// 如果线程池已停止,抛出异常
if (stop) {
throw std::runtime_error("enqueue on stopped ThreadPool");
}
// 添加任务到队列
tasks.emplace([task]() { (*task)(); });
}
// 通知一个等待的线程
condition.notify_one();
return res;
}
// 析构函数,停止所有线程
~ThreadPool() {
{
std::unique_lock<std::mutex> lock(queue_mutex);
stop = true;
}
// 唤醒所有线程
condition.notify_all();
// 等待所有线程完成
for (std::thread &worker : workers) {
if (worker.joinable()) {
worker.join();
}
}
}
private:
std::vector<std::thread> workers; // 工作线程
std::queue<std::function<void()>> tasks; // 任务队列
std::mutex queue_mutex; // 互斥锁保护任务队列
std::condition_variable condition; // 条件变量用于通知线程
std::atomic<bool> stop; // 标志线程池是否停止
};
int main() {
// 创建一个线程池,默认使用硬件支持的线程数
ThreadPool pool(4);
// 提交任务
auto result1 = pool.enqueue([](int a, int b) {
std::this_thread::sleep_for(std::chrono::milliseconds(100));
return a + b;
}, 3, 4);
auto result2 = pool.enqueue([](int a, int b) {
std::this_thread::sleep_for(std::chrono::milliseconds(200));
return a * b;
}, 3, 4);
auto result3 = pool.enqueue([]() {
std::this_thread::sleep_for(std::chrono::milliseconds(300));
return "Hello from thread pool!";
});
// 获取结果
std::cout << "Result 1: " << result1.get() << std::endl;
std::cout << "Result 2: " << result2.get() << std::endl;
std::cout << "Result 3: " << result3.get() << std::endl;
return 0;
}
线程管理:
任务队列:
std::queue 存储待执行的任务std::mutex 保护队列的线程安全std::condition_variable 通知线程有新任务任务提交:
enqueue 方法使用模板和完美转发支持任意可调用对象std::packaged_task 和 std::future 实现异步结果获取线程安全:
这个实现提供了一个基本但完整的线程池功能,可以满足大多数异步任务处理的需求。