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

相关推荐
无限进步_36 分钟前
【Linux】gcc/g++ 编译:从源码到可执行文件的四个阶段
linux·运维·服务器
DianSan_ERP8 小时前
如何通过抖店订单接口实现订单状态管理与履约自动化?
运维·自动化
b***25119 小时前
18650电池点焊机:电阻焊技术如何决定电池组的成败|深圳比斯特自动化
运维·自动化
原来是猿9 小时前
网络计算器:理解序列化与反序列化(中)
linux·运维·服务器·网络·tcp/ip
前端老曹9 小时前
Docker 从入门到放弃:完整指南
运维·docker·容器
AOwhisky10 小时前
虚拟化技术学习笔记
linux·运维·笔记·学习·虚拟化技术
rabbit_pro11 小时前
Docker compose部署Ollama使用模型
linux·运维·docker
笑洋仟12 小时前
docker的overlay2目录占用磁盘空间很大,清理办法
运维·docker·容器
m0_7381207212 小时前
ctfshow靶场SSRF部分——基础绕过到协议攻击解题思路与技巧(一)
服务器·前端·网络·安全·php