栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 系统运维 > 运维 > Linux

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

Linux 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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

线程池封装 说明:

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

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

  • // std::function :https://blog.csdn.net/jinzhu1911/article/details/101307637

  • // template : https://www.cnblogs.com/qicosmos/p/4325949.html

  • // std::future  : 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
#include
#include
#include
#include
#include

class ThreadPool{
private:
    bool m_stop;
    std::vectorm_thread;        //工作线程队列
    std::queue>tasks;  //任务队列
    std::mutex m_mutex;                      //互斥锁
    std::condition_variable m_cv;            //条件变量

public:
    explicit ThreadPool(size_t threadNumber):m_stop(false){
        for(size_t i=0;itask;
                        {
                            std::unique_locklk(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_locklk(m_mutex);
            m_stop=true;
        }
        m_cv.notify_all();
        for(auto& threads:m_thread)
        {
            threads.join();
        }
    }

    template
    auto submit(F&& f,Args&&... args)->std::future{
        auto taskPtr=std::make_shared>(
            std::bind(std::forward(f),std::forward(args)...)
        );
        {
            std::unique_locklk(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
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/289406.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号