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

相关推荐
IT成长日记1 小时前
【Nginx开荒攻略】Nginx虚拟主机配置:从域名、端口到IP的完整指南
linux·运维·服务器·nginx·虚拟主机
taxunjishu1 小时前
DeviceNet 转 Modbus TCP 协议转换在 S7-1200 PLC化工反应釜中的应用
运维·人工智能·物联网·自动化·区块链
迎風吹頭髮2 小时前
UNIX下C语言编程与实践53-UNIX 共享内存控制:shmctl 函数与共享内存管理
服务器·c语言·unix
迎風吹頭髮2 小时前
Linux内核架构浅谈8-Linux内核与UNIX的传承:设计思想与特性差异
linux·运维·架构
黑马金牌编程3 小时前
Linux 服务器常见的性能调优
linux·运维·服务器·性能优化
jieyu11193 小时前
网络、主机安全扫描工具
linux·安全·系统安全
tianyuanwo3 小时前
Linux进程管理中的T状态问题分析与解决体系
linux·运维·进程管理·t状态
liuyao_xianhui4 小时前
Linux_基本指令1
linux·运维·服务器
守望时空334 小时前
Linux挂载NTFS分区指南
linux
shan~~5 小时前
linux达梦数据库操作
linux·数据库·chrome