class fixed_thread_pool {
public:
explicit fixed_thread_pool(size_t thread_count)
: data_(std::make_shared<data>()) {
for (size_t i = 0; i < thread_count; ++i) {
std::thread([data = data_] {
std::unique_lock<std::mutex> lk(data->mtx_);
for (;;) {
if (!data->tasks_.empty()) {
auto current = std::move(data->tasks_.front());
data->tasks_.pop();
lk.unlock(); //这里该线程已经拿到了任务,所以解锁,可以让其它的线程来获取任务
current();
lk.lock(); //执行到这里了说明这个线程是空闲的,可以继续接受其他任务,所以它要去抢到锁用于执行其他的任务
}
else if (data->is_shutdown_) {
break;
}
else {
data->cond_.wait(lk);
}
}
}).detach();
}
}
fixed_thread_pool() = default;
fixed_thread_pool(fixed_thread_pool&&) = default;
~fixed_thread_pool() {
if ((bool)data_) {
{
std::lock_guard<std::mutex> lk(data_->mtx_);
data_->is_shutdown_ = true;
}
data_->cond_.notify_all();
}
}
template <class F>
void execute(F&& task) {
{
std::lock_guard<std::mutex> lk(data_->mtx_);
data_->tasks_.emplace(std::forward<F>(task));
}
data_->cond_.notify_one();
}
private:
struct data {
std::mutex mtx_; // 类内共享互斥量,以便线程间临界区加锁
std::condition_variable cond_; // 条件唤醒
bool is_shutdown_ = false; // 用于关闭线程池
std::queue<std::function<void()>> tasks_; //用于存放要执行的函数
};
std::shared_ptr<data> data_; // 共享智能指针,用于多个线程同时操作data变量