c++11实现线程池

https://github.com/youngqqcn/ThreadPool

class ThreadPool
{
public:
    // the constructor just launches some amount of m_vctWorkers
    ThreadPool(size_t nThreads = std::thread::hardware_concurrency())
        : stop(false)
    {
        if (nThreads <= 0)
        {
            throw std::invalid_argument("more than zero threads expected");
        }

        this->m_vctWorkers.reserve(nThreads);
        for (size_t i = 0; i < nThreads; i++)
        {
            this->m_vctWorkers.emplace_back([this]() {
                while (true)
                {
                    std::function<void()> task;

                    {
                        std::unique_lock<std::mutex> lock(this->m_qMutex);
                        this->condition.wait(
                            lock,
                            [this] {
                                return this->stop || !this->m_queueTasks.empty();
                            });

                        if (this->stop && this->m_queueTasks.empty())
                            return;

                        task = std::move(this->m_queueTasks.front());
                        this->m_queueTasks.pop();
                    }

                    task();
                }
            });
        }
    }

    // deleted copy&move ctors&assignments
    ThreadPool(const ThreadPool &) = delete;
    ThreadPool &operator=(const ThreadPool &) = delete;
    ThreadPool(ThreadPool &&) = delete;
    ThreadPool &operator=(ThreadPool &&) = delete;

    // add new work item to the pool
    template <class F, class... Args>
    auto enqueue(F &&f, Args &&...args)
    {
        using return_type = decltype(f(args...));

        auto task = std::make_shared<std::packaged_task<return_type()>>(
            std::bind(std::forward<F>(f), std::forward<Args>(args)...));

        auto res = task->get_future();
        {
            std::unique_lock<std::mutex> lock(this->m_qMutex);
            this->m_queueTasks.emplace([task]() { (*task)(); });
        }
        this->condition.notify_one();
        return res;
    }

    // the destructor joins all threads
    virtual ~ThreadPool()
    {
        this->stop = true;
        this->condition.notify_all();
        for (std::thread &worker : this->m_vctWorkers)
        {
            worker.join();
        }
    }

private:
    // need to keep track of threads so we can join them
    std::vector<std::thread> m_vctWorkers;
    // the task queue
    std::queue<std::function<void()>> m_queueTasks;

    // synchronization
    std::mutex m_qMutex;
    std::condition_variable condition;
    // m_vctWorkers finalization flag
    std::atomic_bool stop;
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值