Linux-线程池

文章目录


前言

线程池主要是对之前内容的一个巩固,并且初步了解池化概念。


一、线程池是什么?

线程池就是提前开辟好一块空间,随时准备创造新线程来完成任务,可以理解为用空间来换时间,具体实现看以下示例代码。

二、示例代码

cpp 复制代码
#include <pthread.h>
#include <cstdio>
#include <cstdlib>
#include "lockGuard.hpp"
#include "log.hpp"
const int default_ThreadNum = 5;
template <class T>
class ThreadPool
{

public:
    ThreadPool(int thread_num = default_ThreadNum)
    :_thread_num(thread_num)
    {
        pthread_mutex_init(&_mutex,nullptr);
        pthread_cond_init(&_cond,nullptr);
        for (int i = 1; i <= _thread_num; i++)
        {
            char nameBuffer[128];
            snprintf(nameBuffer, sizeof nameBuffer, "Thread %d", i);
            _threadPool.push_back(new Thread(nameBuffer, routine, (void *)this));
            logMessage(NORMAL, "%s 线程创建成功!", nameBuffer);
        }
    }

    bool isEmpty()
    {
        return _task_queue.empty();
    }

    void waitCond()
    {
        pthread_cond_wait(&_cond, &_mutex);
    }

    pthread_mutex_t &getMutex()
    {
        return _mutex;
    }


    T getTask()
    {
        T task = _task_queue.front();
        _task_queue.pop();
        return task;
    }

    std::vector<Thread> &getpool()
    {
        return _threadPool;
    }

    static void *routine(void *args)
    {
        ThreadData *td = (ThreadData *)args;
        ThreadPool<T> *tp = (ThreadPool<T> *)td->_args;
        while (1)
        {
            T task;
            {
                lockGuard lg(&tp->getMutex());
                while (tp->isEmpty())
                    tp->waitCond();
                task = tp->getTask();
            }
            task(td->_name);
        }
    }

    void run()
    {
        for(auto& thread : _threadPool)
        {
            thread->start();
        }
    }

     void pushTask(const T &task)
     {
        lockGuard lg(&_mutex);
        _task_queue.push(task);
        pthread_cond_signal(&_cond);
     }

    ~ThreadPool()
    {
        for(auto& iter: _threadPool)
        {
            iter->join();
            delete iter;
        }
        pthread_mutex_destroy(&_mutex);
        pthread_cond_destroy(&_cond);
    }

private:
    int _thread_num;
    std::vector<Thread*> _threadPool;
    std::queue<T> _task_queue;

    pthread_mutex_t _mutex;
    pthread_cond_t _cond;
};

相关推荐
乱世刀疤24 分钟前
Claude Code提高工作效率案例:自动化分析工作流程时效性,缩短工单流转时长
运维·自动化
AOwhisky27 分钟前
云原生 DevOps 工具链从入门到实战(第二期)——Jenkins安装与基础配置——CICD核心引擎
linux·运维·ci/cd·云原生·jenkins·devops
盐焗鹌鹑蛋39 分钟前
【Linux】基础开发工具yum和vim
linux·运维·vim
AOwhisky1 小时前
Linux(CentOS)系统管理入门笔记(第十四期)——计划任务与进程调度管理:atcron 与 nicechrt
linux·运维·笔记·centos·云计算·进程调度·计划任务
小莫分享1 小时前
sshw:用交互搜索和 Web 配置高效管理 SSH Server
linux·运维·golang·开源·ssh
fthux1 小时前
GitHub Actions自动化运维实战:构建高效可靠的CI/CD流水线
运维·自动化·github
流浪0012 小时前
Linux系统22:——文件(六):目标文件与ELF深度解析:从编译到加载的全景揭秘
linux·运维·服务器
MrDJun2 小时前
长期稳定跑网页监控:TLS 指纹、代理选路与请求节流的工程实践
运维·爬虫·python·网络协议·网站监控
AAA@峥2 小时前
Ceph 集群配置管理完整指南
运维·数据库·分布式·ceph
kidwjb2 小时前
Linux内核-内核信号处理函数
linux·内核·信号处理