linux(番外)线程,锁,条件变量封装;日志与线程池

前言:

也是半个月没更新了,以前学习的时候,总想着把这些代码的编写过程看看就好了,等到回头写博客的时候再开始自己写。真上手的时候才发现,似乎没我想象的顺利,所以本来答应早点更新的东西也拖了这么久,不过至少还是来了,可不就应了linux完结的那一天,我写的"月缺不改光"么;

好啦,废话少说,我们来看看今天要讲些什么

其实我们主要的任务,是要写一个线程池,而我们线程池要用到的头文件有这些......

复制代码
#pragma once
#include <vector>
#include <queue>
#include "Logger.hpp"
#include "Thread.hpp"
#include "Cond.hpp"
#include "Mutex.hpp"

Logger.hpp是我们封装的日志,它又需要什么头文件呢?

复制代码
#include <iostream>
#include <string>
#include <sys/time.h>
#include <time.h>
#include <cstdio>
#include <filesystem>
#include <fstream>
#include "Mutex.hpp"
#include <unistd.h>
#include <sstream>

它也要用到我们的"Mutex.hpp",这是我们封装的锁

而回到我们的线程池,还用到了"Thread.hpp",这是我们封装的线程

还有:"Cond.hpp",这是我们封装的条件变量

以及我们的锁;

所以我们今天要怎么完成呢?

①:先把锁,条件变量,以及线程这三个挂件封装了

②:之后再来实现我们的LOG

③:再然后,我们来正式写我们的线程池

我打算怎么讲?

顺着思路把代码一块一块写出来,最后拼好给出完整代码,中途若有重要事项再单独拎出来讲解;

每一个小章节的最后是完整代码哦:我会命名成*.hpp;

那我们,正式开始

正文:

锁的封装:

我们为什么要封装锁呢?

因为锁的代码太麻烦了,上个锁还要pthread_mutex_lock,这么长一坨,解锁还要pthread_mutex_unlock,太费事了吧;

所以我们要把它进行封装......

复制代码
class Mutex
{
    public:
    Mutex()
    {
        pthread_mutex_init(&_lock,nullptr);
    }
    void lock()
    {
        pthread_mutex_lock(&_lock);
    }
    pthread_mutex_t* ptr()
    {
        return &_lock;
    }
    void unlock()
    {
        pthread_mutex_unlock(&_lock);
    }
    ~Mutex()
    {
        pthread_mutex_destroy(&_lock);
    }
    private:
    pthread_mutex_t _lock;
};

锁的封装,倒也没什么值得注意的地方,至于那个返回原生锁的ptr函数,是因为我们后续在线程池需要用到原生的锁;

那么我们给一个临界区上锁,还是分为两步,一步上锁,一步解锁;我仍然觉得麻烦,怎么办?

复制代码
class LockGuard
{
    public:
    LockGuard(Mutex& _lock)
    :_lockref(_lock)
    {
        _lockref.lock();
    }
    ~LockGuard()
    {
        _lockref.unlock();
    }
    private:
    Mutex& _lockref;
};

我们直接利用锁的生命周期,接下来来段示例代码:

复制代码
void start()
{
    LockGuard lock(_mutex)
    for(int i=0;i<5;i++)
    {
        cnt++;
    }
}

我们只要在临界区之前,定义一个LockGuard变量,那么在临界区走到结尾的时候,我的LockGuard的生命周期也到了,会调用析构函数,而我的析构函数是解锁,那么就无需我人工释放锁了,从而实现了更方便的锁:

所以由此,我们得出了锁的"Mutex.hpp"

Mutex.hpp:

复制代码
#pragma once

#include<iostream>
#include<pthread.h>

class Mutex
{
    public:
    Mutex()
    {
        pthread_mutex_init(&_lock,nullptr);
    }
    void lock()
    {
        pthread_mutex_lock(&_lock);
    }
    pthread_mutex_t* ptr()
    {
        return &_lock;
    }
    void unlock()
    {
        pthread_mutex_unlock(&_lock);
    }
    ~Mutex()
    {
        pthread_mutex_destroy(&_lock);
    }
    private:
    pthread_mutex_t _lock;
};

class LockGuard
{
    public:
    LockGuard(Mutex& _lock)
    :_lockref(_lock)
    {
        _lockref.lock();
    }
    ~LockGuard()
    {
        _lockref.unlock();
    }
    private:
    Mutex& _lockref;
};

条件变量的封装:

条件变量的封装,似乎就没有什么好说的了,注意的是,正因为我们条件变量要用到原生锁,所以我才要在上面的Mutex.hpp中封装获取原生锁指针的函数;

Cond.hpp:

复制代码
#pragma once
#include<iostream>
#include<pthread.h>
#include"Mutex.hpp"

class Cond
{
    public:
    Cond()
    {
        pthread_cond_init(&_cond,nullptr);
    }
    int wait(Mutex &mutex)
    {
        return pthread_cond_wait(&_cond,mutex.ptr());
    }
    int signal()
    {
        return pthread_cond_signal(&_cond);
    }
    int broadcast()
    {
        return pthread_cond_broadcast(&_cond);
    }
    ~Cond()
    {

    }
    private:
    pthread_cond_t _cond;

};

线程的封装:

线程这一块,要注意的可就多了,所以我还使用了域:

注意哦:在此文章中,我们长一点的代码均会使用域,命名风格统一为NS_名称大写_MODULE;

并且呢,我不喜欢在函数里面使用大写,所以我们的函数就都是小写英文咯;

与此同时呢,我们的类名称每个单词开头会大写

线程状态

复制代码
enum class TSTATUS
    {
        THREAD_NEW=1,
        THREAD_RUNNING,
        THREAD_STOP
    };

我们在此设三个状态,新创建的线程,正在运行的线程,停止的线程;

回调函数:

复制代码
using callback_t=std::function<void ()>;

这个的意思其实就是,callback_t是一个返回值类型为void,没有参数的函数;

成员变量:

复制代码
        std::string _name;
        pthread_t _tid;
        TSTATUS _status;
        bool _joinable;
        callback_t _cb;
        void* _result;

分别为:线程名字

线程tid

线程状态(枚举变量)

是否可以被join

要执行的任务(外界给我传)

返回结果(等待被回收)

构造函数:

复制代码
Thread(callback_t cb)
        :_tid(-1),
        _status(TSTATUS::THREAD_NEW),
        _cb(cb),
        _result(nullptr),
        _joinable(true)
        {
            _name="Thread"+std::to_string(gnumber++);
        }

这里没什么好说的

线程启动:

复制代码
bool start()
        {
            int n=pthread_create(&_tid,nullptr,ThreadRoutine,this);
            if(n!=0)
            {
                return false;
            }
            to_running();
            return true;
        }

这里注意事项有点多:

①:ThreadRoutine是?

我们封装的线程回调函数:

复制代码
static void* ThreadRoutine(void* args)
        {
            Thread* self=static_cast<Thread*>(args);
            pthread_setname_np(self->_tid,self->_name.c_str());
            self->_cb();
            self->to_stop();
            return nullptr;
        }

为什么要static?

因为如果不这样写,那么作为成员函数,ThreadRoutine必然会带上this指针,那么就与我要求的线程回调函数形式不一样

我要求的是(void*(void*)),所以我static把它作为类函数,这样才能去掉this指针,使其符合规范

那么,我在ThreadRoutine内部,还是需要访问内部成员的,所以我还是需要把this指针传进来,那么我不就可以通过pthread_creat的最后一个参数把this指针传进来么?

②:至于to_running与to_stop
复制代码
 void to_running()
        {
            _status=TSTATUS::THREAD_RUNNING;
        }
        void to_stop()
        {
            _status=TSTATUS::THREAD_STOP;
        }

由于我的状态不想被随意更改,所以我把它们封装成函数,并且private,这样我线程状态就不会轻易被外界更改

线程分离:

复制代码
void detach()
        {
            if(_status==TSTATUS::THREAD_RUNNING && _joinable)
            {
                pthread_detach(_tid);
                _joinable=false;
            }
            else
            {
                std::cerr<<"detach"<<_name<<"failed"<<std::endl;
            }
        }

如果线程可以被join,并且是运行状态,那么我才可以被detach,只需要注意这两个判断条件即可

线程join:

复制代码
void join()
        {
            if(_joinable)
            {
                int n=pthread_join(_tid,&_result);
                if(n!=0)
                {
                    std::cerr<<"join error"<<_name<<std::endl;
                    return;
                }
                (void)_result;
                _status=TSTATUS::THREAD_STOP;
            }
            else
            {
                std::cerr<<"error,thread joinable:"<<_joinable<<std::endl;
            }
        }

其实也没有什么好说的;

线程终止:

复制代码
 void stop()
        {
            if(_status==TSTATUS::THREAD_RUNNING)
            {
                pthread_cancel(_tid);
                _status=TSTATUS::THREAD_STOP;
            }
        }

把线程杀了,再设置一下状态即可

析构函数:

其实可以不写

Thread.hpp:

接下来给出完整代码:

复制代码
#pragma once

#include<iostream>
#include<pthread.h>
#include<string>
#include<functional>

namespace NS_THREAD_MODULE
{
    using callback_t=std::function<void ()>;
    static int gnumber=1;
    enum class TSTATUS
    {
        THREAD_NEW=1,
        THREAD_RUNNING,
        THREAD_STOP
    };
    std::string suatus2string(TSTATUS status)
    {
        switch(status)
        {
            case TSTATUS::THREAD_NEW:
                return "THREAD_NEW";
            case TSTATUS::THREAD_RUNNING:
                return "THREAD_RUNNING";
            case TSTATUS::THREAD_STOP:
                return "THREAD_STOP";
            default:
                return "unknown";
        }
    }
    class Thread
    {
    private:
        void to_running()
        {
            _status=TSTATUS::THREAD_RUNNING;
        }
        void to_stop()
        {
            _status=TSTATUS::THREAD_STOP;
        }
        static void* ThreadRoutine(void* args)
        {
            Thread* self=static_cast<Thread*>(args);
            pthread_setname_np(self->_tid,self->_name.c_str());
            self->_cb();
            self->to_stop();
            return nullptr;
        }
    public:
        Thread(callback_t cb)
        :_tid(-1),
        _status(TSTATUS::THREAD_NEW),
        _cb(cb),
        _result(nullptr),
        _joinable(true)
        {
            _name="Thread"+std::to_string(gnumber++);
        }
        bool start()
        {
            int n=pthread_create(&_tid,nullptr,ThreadRoutine,this);
            if(n!=0)
            {
                return false;
            }
            to_running();
            return true;
        }
        void detach()
        {
            if(_status==TSTATUS::THREAD_RUNNING && _joinable)
            {
                pthread_detach(_tid);
                _joinable=false;
            }
            else
            {
                std::cerr<<"detach"<<_name<<"failed"<<std::endl;
            }
        }
        void join()
        {
            if(_joinable)
            {
                int n=pthread_join(_tid,&_result);
                if(n!=0)
                {
                    std::cerr<<"join error"<<_name<<std::endl;
                    return;
                }
                (void)_result;
                _status=TSTATUS::THREAD_STOP;
            }
            else
            {
                std::cerr<<"error,thread joinable:"<<_joinable<<std::endl;
            }
        }
        void stop()
        {
            if(_status==TSTATUS::THREAD_RUNNING)
            {
                pthread_cancel(_tid);
                _status=TSTATUS::THREAD_STOP;
            }
        }
        ~Thread()
        {

        }
    private:
        std::string _name;
        pthread_t _tid;
        TSTATUS _status;
        bool _joinable;
        callback_t _cb;
        void* _result;
    };
}

日志:

那么,我们上面三个配件就已经封装完了,接下来进入最难的部分,日志:

期待结果:

①:我们未来希望打出来的日志长这样:

时间+日志等级+pid+哪个文件+第几行

②:并且我想采用c++方式输入:

日志<<"hahahahahahah"

③:与此同时:

我还想让日志可以直接打在显示器上,也可以打到文件里,所以这里有两种策略:

显示器策略与文件策略

那么我们应该如何实现?

成员变量:

只有一个

复制代码
 std::unique_ptr<logstrategy> _strategy;

即我们要选择的策略

两种策略:

基类:
复制代码
class logstrategy
    {
    public:
    virtual ~logstrategy()=default;
    virtual void synclog(const std::string& message)=0;
    };

我直接写成纯虚类,等待子类继承

显示器策略:
复制代码
//策略1,显示器刷新
    class consolestrategy : public logstrategy
    {
        public:
        void synclog(const std::string& message) override
        {
            LockGuard lockguard(_mutex);
            std::cerr<<message<<std::endl;
        }
        private:
        Mutex _mutex;
    };

显示器策略其实没什么好说的,比较重要的也就是加一把锁,防止多个线程一起打,所以我们保证互斥;

文件策略:

这个可就门道多了:

成员:
复制代码
private:
    std::string _path;
    std::string _name;
    Mutex _mutex;
确认路径:
复制代码
    const std::string defaultpath="./log";
    const std::string defaultname="log.txt";

 filelogstrategy(const std::string& path=defaultpath,const std::string& name=defaultname)
    :_path(path),
    _name(name)
    {
        LockGuard lockguard(_mutex);
        if(std::filesystem::exists(_path))
        return;
        try
        {
            std::filesystem::create_directories(_path);
        }
        catch(std::filesystem::filesystem_error &e)
        {
            std::cerr<<e.what()<<std::endl;
        }
    }

上面的两行作为我的缺省值:

文件的话,我没有我直接可以创建的,那路径可就麻烦咯,所以我们重点考虑一下路径:

如果我们的路径存在,我们就return,如果不存在呢,我们就用create_directories创建一条

如何打印:
复制代码
void synclog(const std::string& message) override
    {
        LockGuard lockguard(_mutex);
         if(!_path.empty() && _path.back() != '/')
        {
            _path+="/";
        }
        std::string targetname=_path+_name;
        std::ofstream out(targetname,std::ios::app);
        if(!out.is_open())
        {
            return;
        }
        out<<message<<std::endl;
        out.close();
    }

我们这里采用的是c++的文件操作,还是很简单的吧?打开输出流直接写就好咯

完整的文件打印策略代码
复制代码
//策略2,文件刷新

    const std::string defaultpath="./log";
    const std::string defaultname="log.txt";

    class filelogstrategy : public logstrategy
    {
    public:
    filelogstrategy(const std::string& path=defaultpath,const std::string& name=defaultname)
    :_path(path),
    _name(name)
    {
        LockGuard lockguard(_mutex);
        if(std::filesystem::exists(_path))
        return;
        try
        {
            std::filesystem::create_directories(_path);
        }
        catch(std::filesystem::filesystem_error &e)
        {
            std::cerr<<e.what()<<std::endl;
        }
    }

    void synclog(const std::string& message) override
    {
        LockGuard lockguard(_mutex);
         if(!_path.empty() && _path.back() != '/')
        {
            _path+="/";
        }
        std::string targetname=_path+_name;
        std::ofstream out(targetname,std::ios::app);
        if(!out.is_open())
        {
            return;
        }
        out<<message<<std::endl;
        out.close();
    }
    private:
    std::string _path;
    std::string _name;
    Mutex _mutex;
    };

日志等级:

复制代码
enum class loglevel
    {
        INFO,
        WARNING,
        ERROR,
        FATAL,
        DEBUG
    };

依次为:

正常消息,

警告消息,

错误消息,

严重错误,

调试消息

获取时间:

复制代码
std::string getcurrenttime()
    {
        struct timeval current_time;
        int n = gettimeofday(&current_time, nullptr);
        struct tm struct_time;
        localtime_r(&(current_time.tv_sec), &struct_time);
        char timestr[128];
        snprintf(timestr, sizeof(timestr), "%04d-%02d-%02d %02d:%02d:%02d",
                 struct_time.tm_year + 1900,
                 struct_time.tm_mon + 1,
                 struct_time.tm_mday,
                 struct_time.tm_hour,
                 struct_time.tm_min,
                 struct_time.tm_sec);
        return timestr;
    }

这里用到了几个新函数,其实也没什么值得记忆的必要,用用即可:

值得注意的是,tm结构体它里面存了年月日时分秒这些变量

但是它是自从1900年开始的,所以我们+1900,而月是0-11,所以我们+1

最后呢,执行完毕之后,我的timestr先退化成const char *类型,去构造一个临时的std::string,再将其中的字符拷贝给std::string变量后销毁,返回std::string变量;

至于别的pid,文件名,第几行,都是好获得的,我们就不单独开讲咯:

日志类怎么写:

成员:
复制代码
private:
    loglevel _level;
    std::string _curr_time;
    pid_t _pid;
    std::string _filename;
    int _line;
    std::string _loginfo;
    logger &_log;
构造函数以及刷新策略:
复制代码
    logger()
    {
        useconsolestrategy();
    }
    void useconsolestrategy()
    {
        _strategy=std::make_unique<consolestrategy>();
    }
    void usefilestrategy()
    {
        _strategy=std::make_unique<filelogstrategy>();
    }

我们日志创建的时候,我们默认采用显示器策略:

当然,可以随时更改

内部类表示一条完整的日志内容:
复制代码
 //我要在日志内部写一个类,用来表示一条完整的日志信息:

   class logmessage
   {
    public:
    logmessage(loglevel level,int line,std::string filename,logger &log)
    :_level(level),
    _curr_time(getcurrenttime()),
    _pid(getpid()),
    _filename(filename),
    _line(line),
    _log(log)
    {
        std::stringstream ss;
        ss<<"["<<_curr_time<<"]"
        <<"["<<loglevel2message(_level)<<"]"
        <<"["<<_pid<<"]"
        <<"["<<_filename<<"]"
        <<"["<<_line<<"]"
        <<"-";
        _loginfo=ss.str();
        //上面是左半部分,接下来是右半部分
        //我们仿照c++模式,所以我们要重载<<k
    }

这个stringstream类型的结构体,可以把往他里面打的数据,转化为字符串形式,非常方便

重载<<:
复制代码
        template<typename T>
        logmessage &operator<<(const T& info)
        {
            std::stringstream ss;
            ss<<info;
            _loginfo+=ss.str();
            return *this;
        }

我也不知道输入进来是什么格式,所以我使用模板,再将其用stringstream将其转化为字符串

()重载:

我以后使用日志,不想用类指针->这样的访问了,写起来好麻烦,我想像函数一样访问,所以:

复制代码
 logmessage operator()(loglevel level,std::string filename,int line)
   {
    return logmessage(level,line,filename,*this);
   }
日志析构函数:
复制代码
~logmessage()
    {
        if(_log._strategy)
        {
            _log._strategy->synclog(_loginfo);
        }
    }

这里有小巧思,我们在使用日志的时候,不就是:

log(参数)<<"我要输入的内容"

在这行代码运行期间,我的日志类是个临时变量,只要还在用,就会继续往里面写,不会消失,但如果我这行代码结束呢?临时变量便走到了其生命周期的尽头,调用析构函数;

那么我析构函数是什么?

刷新!这样我的日志就可以按照刷新策略刷到我的显示器或文件里;

宏:

为了让我们的日志更加优雅,所以我们使用宏来优化一下:

复制代码
    #define ENABLE_CONSOLE_LOG_STRATEGY log.useconsolestrategy();
    #define ENABLE_FILE_LOG_STRATEGY log.usefilestrategy();
    #define LOG(level) log(level,__FILE__,__LINE__)

Logger.hpp:

复制代码
#pragma once

#include <iostream>
#include <string>
#include <sys/time.h>
#include <time.h>
#include <cstdio>
#include <filesystem>
#include<fstream>
#include "Mutex.hpp"
#include<unistd.h>
#include<sstream>

namespace NS_LOG_MODULE
{
    enum class loglevel
    {
        INFO,
        WARNING,
        ERROR,
        FATAL,
        DEBUG
    };
    std::string loglevel2message(loglevel level)
    {
        switch(level)
        {
            case loglevel::INFO:
                return "Info";
            case loglevel::WARNING:
                return "Warning";
            case loglevel::ERROR:
                return "Error";
            case loglevel::FATAL:
                return "Fatal";
            case loglevel::DEBUG:
                return "Debug";
            default:
                return "Unknown";
        }
    }

    // 获取时间
    std::string getcurrenttime()
    {
        struct timeval current_time;
        int n = gettimeofday(&current_time, nullptr);
        struct tm struct_time;
        localtime_r(&(current_time.tv_sec), &struct_time);
        char timestr[128];
        snprintf(timestr, sizeof(timestr), "%04d-%02d-%02d %02d:%02d:%02d",
                 struct_time.tm_year + 1900,
                 struct_time.tm_mon + 1,
                 struct_time.tm_mday,
                 struct_time.tm_hour,
                 struct_time.tm_min,
                 struct_time.tm_sec);
        return timestr;
    }

    // 接下来我需要两种刷新策略,
    // 1.往显示器上直接刷新
    // 2.往文件里刷新
    // 策略模式,策略接口
    class logstrategy
    {
    public:
    virtual ~logstrategy()=default;
    virtual void synclog(const std::string& message)=0;
    };
    //策略1,显示器刷新
    class consolestrategy : public logstrategy
    {
        public:
        void synclog(const std::string& message) override
        {
            LockGuard lockguard(_mutex);
            std::cerr<<message<<std::endl;
        }
        private:
        Mutex _mutex;
    };
    //策略2,文件刷新

    const std::string defaultpath="./log";
    const std::string defaultname="log.txt";

    class filelogstrategy : public logstrategy
    {
    public:
    filelogstrategy(const std::string& path=defaultpath,const std::string& name=defaultname)
    :_path(path),
    _name(name)
    {
        LockGuard lockguard(_mutex);
        if(std::filesystem::exists(_path))
        return;
        try
        {
            std::filesystem::create_directories(_path);
        }
        catch(std::filesystem::filesystem_error &e)
        {
            std::cerr<<e.what()<<std::endl;
        }
    }

    void synclog(const std::string& message) override
    {
        LockGuard lockguard(_mutex);
         if(!_path.empty() && _path.back() != '/')
        {
            _path+="/";
        }
        std::string targetname=_path+_name;
        std::ofstream out(targetname,std::ios::app);
        if(!out.is_open())
        {
            return;
        }
        out<<message<<std::endl;
        out.close();
    }
    private:
    std::string _path;
    std::string _name;
    Mutex _mutex;
    };

    //接下来写日志类
    class logger
    {
    public:
    logger()
    {
        useconsolestrategy();
    }
    void useconsolestrategy()
    {
        _strategy=std::make_unique<consolestrategy>();
    }
    void usefilestrategy()
    {
        _strategy=std::make_unique<filelogstrategy>();
    }
   /*  void Debug(const std::string& message)
    {
        if(_strategy!=nullptr)
        {
            _strategy->synclog(message);
        }
    } */

   //我要在日志内部写一个类,用来表示一条完整的日志信息:

   class logmessage
   {
    public:
    logmessage(loglevel level,int line,std::string filename,logger &log)
    :_level(level),
    _curr_time(getcurrenttime()),
    _pid(getpid()),
    _filename(filename),
    _line(line),
    _log(log)
    {
        std::stringstream ss;
        ss<<"["<<_curr_time<<"]"
        <<"["<<loglevel2message(_level)<<"]"
        <<"["<<_pid<<"]"
        <<"["<<_filename<<"]"
        <<"["<<_line<<"]"
        <<"-";
        _loginfo=ss.str();
        //上面是左半部分,接下来是右半部分
        //我们仿照c++模式,所以我们要重载<<k
    }
    ~logmessage()
    {
        if(_log._strategy)
        {
            _log._strategy->synclog(_loginfo);
        }
    }
     template<typename T>
        logmessage &operator<<(const T& info)
        {
            std::stringstream ss;
            ss<<info;
            _loginfo+=ss.str();
            return *this;
        }
    private:
    loglevel _level;
    std::string _curr_time;
    pid_t _pid;
    std::string _filename;
    int _line;
    std::string _loginfo;
    logger &_log;
   };

   //这里要进行一个重载
   logmessage operator()(loglevel level,std::string filename,int line)
   {
    return logmessage(level,line,filename,*this);
   }
    ~logger()
    {
        
    }
    private:
    std::unique_ptr<logstrategy> _strategy;
    };
    logger log;

    #define ENABLE_CONSOLE_LOG_STRATEGY log.useconsolestrategy();
    #define ENABLE_FILE_LOG_STRATEGY log.usefilestrategy();
    #define LOG(level) log(level,__FILE__,__LINE__)
}

线程池:

既然,所有的准备工作都已完成,那么就进入今天最后一步吧?

成员变量:

复制代码
private:
        bool _isrunning;
        std::vector<Thread> _slavers;
        int _slaver_num;
        std::queue<T> _tasks;
        Mutex _mutex;
        Cond _cond;
        int _slaver_sleep_count;
        // 单例模式
        static ThreadPool *_instance;
        static Mutex _lock;
        // 保证单例安全

自上而下分别为:

线程池是否在跑,

我的线程们,

线程个数,

任务队列,

线程池的锁,

条件变量,

有几个线程正在休眠,

剩下两个static变量:

线程池的指针,

创建线程池时,为了防止多次创建的锁

复制代码
    template <typename T>
    ThreadPool<T> *ThreadPool<T>::_instance = nullptr;
    template <typename T>
    Mutex ThreadPool<T>::_lock;

static变量,我们在类外初始化;

复制代码
        void handlertask()
        {
            char name[128];
            pthread_getname_np(pthread_self(), name, sizeof(name));
            while (true)
            {
                _mutex.lock();
                while (_tasks.empty() && _isrunning)
                {
                    _slaver_sleep_count++;
                    _cond.wait(_mutex);
                    _slaver_sleep_count--;
                }
                // 如果我线程池停了,且任务队列为空
                if (!_isrunning && _tasks.empty())
                {
                    _mutex.unlock();
                    break;
                }
                // 如果有任务了
                T task = _tasks.front();
                _tasks.pop();
                _mutex.unlock();
                LOG(loglevel::INFO) << "我是线程:" << name;
                task();
            }
        }

任务:

复制代码
        void handlertask()
        {
            char name[128];
            pthread_getname_np(pthread_self(), name, sizeof(name));
            while (true)
            {
                _mutex.lock();
                while (_tasks.empty() && _isrunning)
                {
                    _slaver_sleep_count++;
                    _cond.wait(_mutex);
                    _slaver_sleep_count--;
                }
                // 如果我线程池停了,且任务队列为空
                if (!_isrunning && _tasks.empty())
                {
                    _mutex.unlock();
                    break;
                }
                // 如果有任务了
                T task = _tasks.front();
                _tasks.pop();
                _mutex.unlock();
                LOG(loglevel::INFO) << "我是线程:" << name;
                task();
            }
        }

首先给我在内核中把线程名字改掉了,之后进行上锁抢夺任务,抢到任务我就离开,去执行我的任务

启动:

复制代码
        void start()
        {
            if (_isrunning)
            {
                LOG(loglevel::ERROR) << "the pool is already running";
                return;
            }
            _isrunning = true;
            for (auto &slaver : _slavers)
            {
                slaver.start();
            }
        }

这个也很简单,不就是让我每一个线程都调用自己的start么

构造函数:

复制代码
        ThreadPool(int number = defaultnumber)
            : _slaver_sleep_count(0),
              _slaver_num(number),
              _isrunning(false)
        {
            for (int i = 0; i < _slaver_num; i++)
            {
                auto f = std::bind(&ThreadPool::handlertask, this);
                _slavers.emplace_back(f);
                /* _slavers.emplace_back([this](){
                    this->handlertask();
                }); */
            }
        }
        // 赋值拷贝禁掉
        ThreadPool &operator=(const ThreadPool &) = delete;
        ThreadPool(const ThreadPool &) = delete;

之所以禁掉赋值拷贝,因为我们今天是单例模式,所以我们只允许存在一个线程池,同时,我们的构造函数也要private化:

我们初始化的时候,此时睡眠的线程为0,用外界传进来的number创建对应个数的线程,并且线程池此时并未跑起来:

那么接下来,就是我认为最绕的地方了:

首先,为了构造我封装的线程,我需要返回值为void,无参函数,但显然,我需要this指针,我可以用lambda,也可以用bind,让handlertask变成一个返回值为void,无参的函数

此时,这个lambda表达式,被我用来构造Thread对象了:

然后,这个lambda就作为cb,传给了_cb,

接下来,

当我调用start的时候,我的一个个线程也调用start;

此时:线程正式创建(原生线程,不是我封装的线程)

而我的线程创建以后,去执行ThreadRoutine,

而ThreadRoutine中又会调用_cb,那不就是我的lambda么!

停止:

复制代码
 void stop()
        {
            // version1, 简单粗暴版本
            /*  if (!_isrunning)
             {
                 LOG(loglevel::WARNING) << "the pool is not already running";
                 return;
             }
             _isrunning = false;
             for (auto &thread : _slavers)
             {
                 thread.stop();
             } */
            // version 2
            _mutex.lock();
            _isrunning = false;
            if (_slaver_sleep_count > 0)
            {
                _cond.broadcast();
            }
            _mutex.unlock();
        }

这里有两个版本,第一个是直接把线程杀了

而第二个是:

让所有线程先全部醒来,然后去看任务队列中还有没有任务,同时把_isrunning设置为false,这样handlertask那里的判断就会发生改变,直到所有任务全部完成,那么我的线程会break,从而自然结束

等待:

复制代码
        void wait()
        {
            for (auto &slaver : _slavers)
            {
                slaver.join();
            }
        }

就是把所有线程都等一遍;

任务入队列:

复制代码
        void enqueue(T in)
        {
            _mutex.lock();
            _tasks.push(in);
            if (_slaver_sleep_count > 0)
                _cond.signal();
            _mutex.unlock();
        }

这个就是把任务加入我们的队列之中,如果有线程在沉眠,直接叫醒一个让他去做任务;

ThreadPool.hpp

复制代码
#pragma once
#include <vector>
#include <queue>
#include "Logger.hpp"
#include "Thread.hpp"
#include "Cond.hpp"
#include "Mutex.hpp"

namespace NS_THREAD_POOL_MODULE
{
    const int defaultnumber = 5;
    using namespace NS_LOG_MODULE;
    using namespace NS_THREAD_MODULE;

    template <typename T>
    class ThreadPool
    {
    private:
        void handlertask()
        {
            char name[128];
            pthread_getname_np(pthread_self(), name, sizeof(name));
            while (true)
            {
                _mutex.lock();
                while (_tasks.empty() && _isrunning)
                {
                    _slaver_sleep_count++;
                    _cond.wait(_mutex);
                    _slaver_sleep_count--;
                }
                // 如果我线程池停了,且任务队列为空
                if (!_isrunning && _tasks.empty())
                {
                    _mutex.unlock();
                    break;
                }
                // 如果有任务了
                T task = _tasks.front();
                _tasks.pop();
                _mutex.unlock();
                LOG(loglevel::INFO) << "我是线程:" << name;
                task();
            }
        }

    private:
        ThreadPool(int number = defaultnumber)
            : _slaver_sleep_count(0),
              _slaver_num(number),
              _isrunning(false)
        {
            for (int i = 0; i < _slaver_num; i++)
            {
                auto f = std::bind(&ThreadPool::handlertask, this);
                _slavers.emplace_back(f);
                /* _slavers.emplace_back([this](){
                    this->handlertask();
                }); */
            }
        }
        // 赋值拷贝禁掉
        ThreadPool &operator=(const ThreadPool &) = delete;
        ThreadPool(const ThreadPool &) = delete;

    public:
        static ThreadPool *instance()
        {
            if (nullptr == _instance)
            {
                LockGuard lockguard(_lock);

                if (nullptr == _instance)
                {
                    // 第一次调用
                    _instance = new ThreadPool();
                    _instance->start();
                    LOG(loglevel::INFO) << "第一次调用";
                }
            }
            return _instance;
        }
        void start()
        {
            if (_isrunning)
            {
                LOG(loglevel::ERROR) << "the pool is already running";
                return;
            }
            _isrunning = true;
            for (auto &slaver : _slavers)
            {
                slaver.start();
            }
        }
        void stop()
        {
            // version1, 简单粗暴版本
            /*  if (!_isrunning)
             {
                 LOG(loglevel::WARNING) << "the pool is not already running";
                 return;
             }
             _isrunning = false;
             for (auto &thread : _slavers)
             {
                 thread.stop();
             } */
            // version 2
            _mutex.lock();
            _isrunning = false;
            if (_slaver_sleep_count > 0)
            {
                _cond.broadcast();
            }
            _mutex.unlock();
        }
        void wait()
        {
            for (auto &slaver : _slavers)
            {
                slaver.join();
            }
        }
        void enqueue(T in)
        {
            _mutex.lock();
            _tasks.push(in);
            if (_slaver_sleep_count > 0)
                _cond.signal();
            _mutex.unlock();
        }
        ~ThreadPool()
        {
        }

    private:
        bool _isrunning;
        std::vector<Thread> _slavers;
        int _slaver_num;
        std::queue<T> _tasks;
        Mutex _mutex;
        Cond _cond;
        int _slaver_sleep_count;
        // 单例模式
        static ThreadPool *_instance;
        static Mutex _lock;
        // 保证单例安全
    };
    template <typename T>
    ThreadPool<T> *ThreadPool<T>::_instance = nullptr;
    template <typename T>
    Mutex ThreadPool<T>::_lock;
}

main.cc(测试)

复制代码
#include"Logger.hpp"
#include"ThreadPool.hpp"

#include<memory>

using namespace NS_LOG_MODULE;
using namespace NS_THREAD_POOL_MODULE;
using task_t=std::function<void()>;

int main()
{
    ENABLE_CONSOLE_LOG_STRATEGY;
 /*    std::unique_ptr tp=std::make_unique<ThreadPool<task_t>>();
    tp->start(); */
    ThreadPool<task_t>::instance();

    int cnt=10;
    while(cnt--)
    {
        ThreadPool<task_t>::instance()->enqueue([](){
            LOG(loglevel::INFO)<<"我是一个任务,我正在运行";
        });
        sleep(1);
    }
    ThreadPool<task_t>::instance()->stop();
    ThreadPool<task_t>::instance()->wait();
    sleep(5);
}

wuchun@VM-0-10-ubuntu:~/11_17/Logger$ ./threadpool
[2026-11-23 16:27:16][Info][3344564][ThreadPool.hpp][78]-第一次调用
[2026-11-23 16:27:16][Info][3344564][ThreadPool.hpp][42]-我是线程:Thread3
[2026-11-23 16:27:16][Info][3344564][main.cc][21]-我是一个任务,我正在运行
[2026-11-23 16:27:17][Info][3344564][ThreadPool.hpp][42]-我是线程:Thread1
[2026-11-23 16:27:17][Info][3344564][main.cc][21]-我是一个任务,我正在运行
[2026-11-23 16:27:18][Info][3344564][ThreadPool.hpp][42]-我是线程:Thread4
[2026-11-23 16:27:18][Info][3344564][main.cc][21]-我是一个任务,我正在运行
[2026-11-23 16:27:19][Info][3344564][ThreadPool.hpp][42]-我是线程:Thread5
[2026-11-23 16:27:19][Info][3344564][main.cc][21]-我是一个任务,我正在运行
[2026-11-23 16:27:20][Info][3344564][ThreadPool.hpp][42]-我是线程:Thread3
[2026-11-23 16:27:20][Info][3344564][main.cc][21]-我是一个任务,我正在运行
[2026-11-23 16:27:21][Info][3344564][ThreadPool.hpp][42]-我是线程:Thread2
[2026-11-23 16:27:21][Info][3344564][main.cc][21]-我是一个任务,我正在运行
[2026-11-23 16:27:22][Info][3344564][ThreadPool.hpp][42]-我是线程:Thread1
[2026-11-23 16:27:22][Info][3344564][main.cc][21]-我是一个任务,我正在运行
[2026-11-23 16:27:23][Info][3344564][ThreadPool.hpp][42]-我是线程:Thread4
[2026-11-23 16:27:23][Info][3344564][main.cc][21]-我是一个任务,我正在运行
[2026-11-23 16:27:24][Info][3344564][ThreadPool.hpp][42]-我是线程:Thread5
[2026-11-23 16:27:24][Info][3344564][main.cc][21]-我是一个任务,我正在运行
[2026-11-23 16:27:25][Info][3344564][ThreadPool.hpp][42]-我是线程:Thread3
[2026-11-23 16:27:25][Info][3344564][main.cc][21]-我是一个任务,我正在运行

OK,大功告成

尾:

最近很喜欢一首诗,在此贴出,与诸位共赏:

大雨落幽燕,

白浪滔天,

秦皇岛外打鱼船。

一片汪洋都不见,

知向谁边?

往事越千年,

魏武挥鞭,

东临碣石有遗篇。

萧瑟秋风今又是,

换了人间。

相关推荐
S_WEAN20 分钟前
【C++】STL - Priority_queue的使用及模拟实现与仿函数
开发语言·c++
Rain的Java大神之路25 分钟前
前端转 Java 全栈:用 AI 两天交付一个能跑的 Demo,踩坑全记录
java·前端·后端
2401_858286111 小时前
LKDS8.Linux内核的双向链表代码解析(8) 拼接链表、获取链表首/尾元素的宏、list_for_each系列的安全版本的宏
linux·链表
星落梦生1 小时前
Tlias前端案例涉及知识点 (14)
开发语言·前端·javascript
渴了喝洗衣液1 小时前
第一阶段项目
linux·运维·服务器
Moment2 小时前
27B 的本地模型也能做知识图谱?太强了!😍😍😍
前端·后端·面试
维克兜率天2 小时前
【维克】KDJ量化实战:如何用它判断买卖点?
前端
俊俊几年的2 小时前
嵌入式 Linux 应用开发:CMake 详解与交叉编译实践
linux·c++·嵌入式·cmake·linux应用开发
维克兜率天4 小时前
【维克】RSI相对强弱指数:判断多空力量的温度计
前端