CPP服务器06--线程池实现(2)

本文介绍了一个基于C++11标准实现的线程池类,包括工作线程、任务队列、互斥锁和条件变量等关键组件。线程池支持任务提交并返回future,适用于异步任务执行。同时,文章提供了代码示例,展示了如何创建和使用线程池。

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

线程池封装

说明:

上篇文章中的线程池,功能相对完整,有管理调度线程.但接口定义通用性差,需要修改,奈何目前水平不够,只能先找一个能用的替换,以后再改吧.

阅读建议:
  • // std::thread :https://subingwen.cn/cpp/thread/

  • // std::function :https://blog.youkuaiyun.com/jinzhu1911/article/details/101307637

  • // template<typename F,typename… Args> : https://www.cnblogs.com/qicosmos/p/4325949.html

  • // std::future<decltype(f(args…))>  : https://www.zhihu.com/question/447107869

  • // std::move std::forward : https://www.jianshu.com/p/b90d1091a4ff

  • // std::mutex

  • // std::condition_variable

  • // std::unique_lock

  • // std::make_shared

#ifndef THREADPOOL_H
#define THREADPOOL_H

#include<thread>
#include<condition_variable>
#include<mutex>
#include<vector>
#include<queue>
#include<future>

class ThreadPool{
private:
    bool m_stop;
    std::vector<std::thread>m_thread;        //工作线程队列
    std::queue<std::function<void()>>tasks;  //任务队列
    std::mutex m_mutex;                      //互斥锁
    std::condition_variable m_cv;            //条件变量

public:
    explicit ThreadPool(size_t threadNumber):m_stop(false){
        for(size_t i=0;i<threadNumber;++i)
        {
            m_thread.emplace_back( //任务队列尾插任务--参数为lambda函数
                [this](){          //--参数为lambda函数
                    for(;;)
                    {
                        std::function<void()>task;
                        {
                            std::unique_lock<std::mutex>lk(m_mutex);
                            m_cv.wait(lk,[this](){ return m_stop||!tasks.empty();});
                            if(m_stop&&tasks.empty()) return;
                            task=std::move(tasks.front());
                            tasks.pop();
                        }
                        task();
                    }
                }
            );
        }
    }

    ThreadPool(const ThreadPool &) = delete; //禁止拷贝构造
    ThreadPool(ThreadPool &&) = delete;

    ThreadPool & operator=(const ThreadPool &) = delete; //禁止赋值
    ThreadPool & operator=(ThreadPool &&) = delete;

    ~ThreadPool(){
        {
            std::unique_lock<std::mutex>lk(m_mutex);
            m_stop=true;
        }
        m_cv.notify_all();
        for(auto& threads:m_thread)
        {
            threads.join();
        }
    }

    template<typename F,typename... Args>
    auto submit(F&& f,Args&&... args)->std::future<decltype(f(args...))>{
        auto taskPtr=std::make_shared<std::packaged_task<decltype(f(args...))()>>(
            std::bind(std::forward<F>(f),std::forward<Args>(args)...)
        );
        {
            std::unique_lock<std::mutex>lk(m_mutex);
            if(m_stop) throw std::runtime_error("submit on stopped ThreadPool");
            tasks.emplace([taskPtr](){ (*taskPtr)(); });
        }
        m_cv.notify_one();
        return taskPtr->get_future();

    }
};

#endif //THREADPOOL_H
                     

代码引用

  • 基于C++11实现线程池 - Skykey的文章 - 知乎
    https://zhuanlan.zhihu.com/p/367309864
  • https://github.com/Aged-cat/WebServer
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

ColaForced

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值