C++ 线程池

#include <iostream>
#include <queue>
#include <thread>
#include <mutex>
#include <condition_variable>

class ThreadPool {
public:
    // 定义ThreadPool类的构造函数
    ThreadPool(size_t num_threads) {
        // 创建线程并将它们添加到线程池
        for (size_t i = 0; i < num_threads; ++i) {
            threads.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();
                    }
                    // 执行任务
                    task();
                }
            });
        }
    }

    // 为ThreadPool类定义enqueue函数
    template<class F, class... Args>
    void enqueue(F&& f, Args&&... args) {
        {
            // 锁定队列并将任务添加到队列中
            std::unique_lock<std::mutex> lock(queue_mutex);
            tasks.emplace([=] { std::forward<F>(f)(std::forward<Args>(args)...); });
        }
        // 通知一个线程有任务已添加到队列中
        condition.notify_one();
    }

    // 定义ThreadPool类的析构函数
    ~ThreadPool() {
        {
            // 锁定队列并将stop设置为true
            std::unique_lock<std::mutex> lock(queue_mutex);
            stop = true;
        }
        // 通知所有线程线程池已经停止
        condition.notify_all();
        // 连接线程池中的所有线程
        for (std::thread &thread : threads) {
            thread.join();
        }
    }

private:
    // 定义ThreadPool类所需的变量
    std::vector<std::thread> threads;
    std::queue<std::function<void()>> tasks;
    std::mutex queue_mutex;
    std::condition_variable condition;
    bool stop = false;
};


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值