这是一个非常标准的C++线程池实现,使用了现代C++11特性。让我详细解释一下这个实现的各个部分,并指出一些可以优化的地方:
### 核心组件解析
1. **工作线程管理**:
“`cpp
std::vector<std::thread> workers;
“`
– 使用vector存储工作线程
– 在构造函数中创建指定数量的线程
2. **任务队列**:
“`cpp
std::queue<std::function<void()>> tasks;
“`
– 存储待执行的任务(封装为void()函数)
– 线程安全通过互斥锁保证
3. **同步机制**:
“`cpp
std::mutex queue_mutex;
std::condition_variable condition;
“`
– 互斥锁保护任务队列
– 条件变量用于线程间通信
– 工作线程等待条件变量:`condition.wait(lock, predicate)`
4. **任务提交**:
“`cpp
template<class F, class… Args>
auto enqueue(F&& f, Args&&… args)
-> std::future<typename std::result_of<F(Args…)>::type>
“`
– 使用完美转发(`forward`)保持参数类型
– 返回`std::future`获取异步结果
– 使用`std::packaged_task`封装任务
5. **工作线程循环**:
“`cpp
while(true) {
// …
task = std::move(this->tasks.front());
this->tasks.pop();
task();
}
“`
– 每个工作线程不断从队列获取任务并执行
– 使用`std::move`避免不必要的拷贝
### 值得优化的地方
1. **使用`std::invoke_result`代替`std::result_of`**:
– C++17起`std::result_of`被弃用,应使用`std::invoke_result`
“`cpp
-> std::future<typename std::invoke_result_t<F, Args…>>
“`
2. **添加线程安全停止机制**:
“`cpp
void shutdown_now() {
{
std::unique_lock<std::mutex> lock(queue_mutex);
stop = true;
// 清空队列中的剩余任务
while(!tasks.empty()) tasks.pop();
}
condition.notify_all();
for(auto& worker : workers) {
if(worker.joinable()) worker.join();
}
}
“`
3. **支持任务优先级**:
“`cpp
// 使用优先队列
std::priority_queue<Task, std::vector<Task>, Compare> tasks;
“`
4. **添加线程池状态检查**:
“`cpp
bool is_running() const {
std::unique_lock<std::mutex> lock(queue_mutex);
return !stop;
}
“`
5. **更健壮的任务执行**:
“`cpp
try {
task();
} catch (…) {
// 记录异常但不影响线程运行
}
“`
### 完整优化版本
“`cpp
#include <vector>
#include <queue>
#include <thread>
#include <mutex>
#include <condition_variable>
#include <functional>
#include <future>
#include <iostream>
#include <type_traits> // 使用 invoke_result
class ThreadPool {
public:
explicit ThreadPool(size_t threads) : stop(false) {
workers.reserve(threads);
for (size_t i = 0; i < threads; ++i) {
workers.emplace_back([this] {
while (true) {
std::function<void()> task;
{
std::unique_lock<std::mutex> lock(this->queue_mutex);
this->condition.wait(lock, [this] {
return this->stop || !this->tasks.empty();
});
if (this->stop && this->tasks.empty())
return;
task = std::move(this->tasks.front());
this->tasks.pop();
}
try {
task();
} catch (…) {
// 异常处理
}
}
});
}
}
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…>;
if (stop) {
throw std::runtime_error(“enqueue on stopped ThreadPool”);
}
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(queue_mutex);
tasks.emplace([task]() { (*task)(); });
}
condition.notify_one();
return res;
}
void shutdown(bool wait_completion = true) {
{
std::unique_lock<std::mutex> lock(queue_mutex);
stop = true;
if (!wait_completion) {
// 清空任务队列
while (!tasks.empty()) tasks.pop();
}
}
condition.notify_all();
for (std::thread& worker : workers) {
if (worker.joinable()) worker.join();
}
}
~ThreadPool() {
shutdown(true);
}
private:
std::vector<std::thread> workers;
std::queue<std::function<void()>> tasks;
std::mutex queue_mutex;
std::condition_variable condition;
bool stop;
};
“`
### 使用示例
“`cpp
int main() {
ThreadPool pool(4);
// 提交多个任务
std::vector<std::future<int>> results;
for (int i = 0; i < 8; ++i) {
results.emplace_back(
pool.enqueue([i] {
std::this_thread::sleep_for(std::chrono::milliseconds(100));
return i * i;
})
);
}
// 获取结果
for (auto& result : results) {
std::cout << result.get() << ‘ ‘;
}
std::cout << std::endl;
// 提交字符串处理任务
auto str_task = pool.enqueue([](const std::string& a, const std::string& b) {
return a + ” ” + b;
}, “Hello”, “ThreadPool”);
std::cout << str_task.get() << std::endl;
// 手动关闭线程池(可选)
pool.shutdown();
return 0;
}
“`
### 关键改进点
1. **使用C++17特性**:
– `std::invoke_result_t` 替代弃用的 `std::result_of`
2. **增强的关闭机制**:
– `shutdown()` 方法支持两种模式:
– 等待所有任务完成(默认)
– 立即停止(清空任务队列)
3. **异常安全**:
– 任务执行包裹在try-catch块中
– 防止单个任务异常导致线程退出
4. **资源管理**:
– 析构函数自动调用shutdown
– 检查线程是否可join
5. **接口优化**:
– 更清晰的错误处理
– 提前检查线程池状态
这个实现保持了简洁性(约60行),同时增加了健壮性和现代C++特性,适合面试展示。
何时使用哪种?
使用 lock_guard
当:
✅ 锁的范围清晰且连续
✅ 不需要中途解锁
✅ 不与条件变量配合
✅ 追求极致性能的简单锁定
✅ 代码简洁性优先
使用 unique_lock
当:
✅ 需要配合条件变量
✅ 需要手动控制锁定/解锁时机
✅ 需要延迟锁定或尝试锁定
✅ 需要转移锁的所有权
✅ 需要更精细的锁管理策略
✅ 处理复杂的多线程交互
评论(0)