【算法】【编程】C++实现线程池

本文介绍了如何用C++实现一个基础的线程池,包含线程数组、任务队列,通过条件变量和flag控制任务分配与线程唤醒,适合初学者理解多线程编程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

线程池主要包含一个线程数组、一个任务队列,接口添加任务,分发给线程;通过条件变量和flag唤醒线程。
参考了知乎与Github的代码,一个较简易的实现:

#include <atomic>
#include <condition_variable>
#include <functional>
#include <queue>
#include <thread>
#include <vector>
class Pool {
   public:
    Pool(const int thread_num = 6) : thread_num_(thread_num) {
        while (threads_.size() < thread_num_) {
            threads_.emplace_back([this] {
                for (;;) {
                    std::function<void()> task;
                    {
                        std::unique_lock<std::mutex> lck(this->mtx_);
                        this->cond_var_.wait(lck, [this] {
                            return this->is_stoped || !this->tasks_.empty();
                        });
                        if (this->is_stoped || this->tasks_.empty()) {
                            return;
                        }
                        task = std::move(this->tasks_.front());
                        this->tasks_.pop();
                    }
                    task();
                };
            });
        }
    }
    template <typename F, typename... Args>
    void Add(F &&f, Args &&... args) {
        if (is_stoped) {
            return;
        }
        std::unique_lock<std::mutex> lck(this->mtx_);
        tasks_.push([=]() { f(args...); });
        cond_var_.notify_all();
    }
    void Stop() {
        is_stoped = true;
        std::unique_lock<std::mutex> lck(this->mtx_);
        while (!tasks_.empty()) {
            tasks_.pop();
        }
        cond_var_.notify_all();
        for(auto &t: threads_){
            if(t.joinable()){
                t.join();
            }
        }
    }
    ~Pool() {
        Stop();
        threads_.clear();
    }

   private:
    const int thread_num_;
    std::mutex mtx_;
    std::condition_variable cond_var_;
    std::atomic_bool is_stoped{false};
    std::vector<std::thread> threads_;
    std::queue<std::function<void()>> tasks_;
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值