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;
};

相关推荐
2401_834636991 小时前
Linux 负载均衡全实战:Nginx+HAProxy+LVS 从原理到落地
linux·nginx·负载均衡
鹏大师运维7 小时前
为什么信创电脑装软件总提示“软件包架构不匹配”?
linux·运维·架构·国产化·麒麟·deb·统信uos
007张三丰7 小时前
软件测试专栏(11/20):测试框架开发:pytest深度解析与插件体系
运维·服务器·自动化测试·pytest·测试框架
weixin_604236678 小时前
华三 路由器 极简核心配置
运维·服务器·网络·h3c·h3c路由器
鹤落晴春9 小时前
【Linux复习】管理SELinux安全性
linux·运维·服务器
yz_aiks9 小时前
Linux Jar包配置Systemd自启动实战:从排查到配置全流程
linux·python·jar·自启动·systemd
AI智图坊9 小时前
多件装组合SKU图的批量生产效率分析:从PS手工到AI自动化的工作流改造
大数据·运维·人工智能·gpt·ai作画·自动化·aigc
bjzhang7510 小时前
CentOS下安装MySQL详解
linux·mysql·centos
Jason_chen12 小时前
Linux 6.2 音频机制深度解析:AI驱动的低延迟音频与零信任音频安全架构
linux
下午写HelloWorld12 小时前
Linux系统及Ubuntu常用指令
linux·ubuntu·操作系统