当前位置: 代码网 > it编程>编程语言>C/C++ > C++缓存线程池CachedThreadPool原理、实现与对比解析

C++缓存线程池CachedThreadPool原理、实现与对比解析

2026年05月14日 C/C++ 我要评论
前言在高并发编程场景中,线程池是提升程序性能、降低资源消耗的核心组件。不同于固定大小的线程池,缓存线程池(cachedthreadpool) 能够根据任务量动态调整线程数量 —&mdash

前言

在高并发编程场景中,线程池是提升程序性能、降低资源消耗的核心组件。不同于固定大小的线程池,缓存线程池(cachedthreadpool) 能够根据任务量动态调整线程数量 —— 任务繁忙时创建新线程,空闲时回收多余线程,兼顾了高并发处理能力和资源利用率。

一、缓存线程池的核心设计理念

缓存线程池的核心目标是解决任务量波动场景下的线程资源高效管理,其设计理念围绕四大核心目标展开:

  • 动态扩缩容:核心线程数保持稳定,任务积压时临时创建新线程,空闲线程超时时自动回收;
  • 任务异步调度:通过线程安全的任务队列解耦任务提交与执行;
  • 资源可控:限制最大线程数,避免无限制创建线程导致系统资源耗尽;
  • 优雅退出:支持线程池停止时等待所有任务执行完毕,避免任务丢失。

本文实现的缓存线程池核心结构如下:

  • 线程安全的任务队列(syncqueue):存储待执行的任务,支持阻塞 / 超时获取任务;
  • 线程管理模块:维护线程集合,统计核心线程、空闲线程、当前线程数;
  • 动态扩缩容逻辑:根据空闲线程数和任务队列状态创建 / 回收线程;
  • 任务提交接口:支持普通任务和带返回值的异步任务提交。

二、核心组件拆解

2.1 线程安全的任务队列(syncqueue)

任务队列是线程池的 “消息中枢”,需要保证多线程下的安全读写,同时支持 “队列满时阻塞提交”“队列空时阻塞获取”“超时退出” 等核心能力。

核心实现细节

#include <list>
#include <vector>
#include <deque>
#include <queue>
#include <mutex>
#include <condition_variable>
#include <iostream>
using namespace std;
#include "logger.hpp"
#define questop 2
#define queempty 1
#define ok 0
#ifndef sync_queue_1_hpp
#define sync_queue_1_hpp
namespace tulun
{
    static const size_t maxtaskcount = 500;
    template <class t> // task = 队列里存的类型
    class syncqueue
    {
    private:
        std::deque<t> m_queue;              // 底层容器:双端队列(存任务),头尾操作o(1)
        mutable std::mutex m_mutex;         // 互斥锁,保护队列所有共享操作
        std::condition_variable m_notempty; // 条件变量:队列非空,唤醒消费者线程
        std::condition_variable m_notfull;  // 条件变量:队列未满,唤醒生产者线程
        std::condition_variable m_waitstop; // 条件变量:等待队列为空再停止
        int m_maxsize;                      // 队列最大容量上限
        bool m_needstop;                    // true停止标记(初始为false)
        int m_waittime = 100;               // 超时等待时间,单位ms
                                            // 判断队列是否满
        bool isfull() const
        {
            bool full = m_queue.size() >= m_maxsize;
            // log_info << "full: " << full;
            //  log_fatal<<"full: "<<full;
            return full;
        }
        // 判断队列是否为空
        bool isempty() const
        {
            bool empty = m_queue.empty();
            // log_info << "empty: " << empty;
            return empty;
        }
        template <class f> // f 传进来的参数类型
        int add(f &&task)
        {
            std::unique_lock<std::mutex> locker(m_mutex); // 加锁
            // if(isfull()) return ;
            // m_notfull.wait(locker,[this]()->bool{
            //     return m_needstop || !isfull();
            // });
            // 队列满 && 不停止 → 等待
            // while (!m_needstop && isfull())
            //{
            //    auto tag = m_notfull.wait_for(locker, std::chrono::milliseconds(m_waittime)); // 阻塞,等待不满
            //    if (tag == std::cv_status::timeout && isfull())
            //    {
            //       return 1;
            //    }
            //}
            // 带超时等待:队列未满 或 线程池停止 就解除阻塞
            auto tag = m_notfull.wait_for(locker,
                                          std::chrono::milliseconds(m_waittime),
                                          [this]() -> bool
                                          {
                                              return m_needstop || !isfull();
                                          }); // lambda 返回 true → 停止等待,继续往下执行代码
            if (m_needstop)
            {
                return 2; // 线程池已停止,入队失败
            }
            if (!tag) // 超时队列依旧满,触发拒绝策略
            {
                return 1; // isfull() true;
            }
            // 完美转发,零拷贝将任务放入队列尾部
            m_queue.push_back(std::forward<f>(task)); // 放入队列
            m_notempty.notify_all();                  // 唤醒消费者:有活干了!
            return 0;
        }
    public:
        syncqueue(int maxsize = maxtaskcount)
            : m_maxsize(maxsize),
              m_needstop(false)
        {
        }
        ~syncqueue()
        {
            if (!m_needstop)
            {
                stop();
            }
        }
        syncqueue(const syncqueue &) = delete;
        syncqueue &operator=(const syncqueue &) = delete;
        // 生产者 put(放任务)
        int put(const t &task)
        {
            return add(task);
        }
        int put(t &&task)
        {
            return add(std::forward<t>(task));
        }
        // 消费者 take(取任务)
        int take(t &task)
        {
            std::unique_lock<std::mutex> locker(m_mutex); // 加锁
            // 队列空 && 不停止 → 等待
            // while (!m_needstop && isempty())
            // {
            //     m_notempty.wait(locker); // 阻塞,等待不为空
            // }
            bool tag = m_notempty.wait_for(locker,
                                           std::chrono::milliseconds(m_waittime),
                                           [this]() -> bool
                                           {
                                               return m_needstop || !isempty();
                                           });
            if (m_needstop)
            {
                return 2;
            }
            if (!tag)
            {
                return 1;
            }
            task = m_queue.front();
            m_queue.pop_front();    // 取出任务
            m_notfull.notify_all(); // 唤醒生产者:有空位啦!
            return 0;
        }
        // 批量取任务(高性能)
        int task(std::deque<t> &tqu)
        {
            std::unique_lock<std::mutex> locker(m_mutex);
            bool tag = m_notempty.wait_for(locker,
                                           std::chrono::milliseconds(m_waittime),
                                           [this]() -> bool
                                           {
                                               return m_needstop || !isempty();
                                           });
            if (m_needstop)
            {
                return 2;
            }
            if (!tag)
            {
                return 1;
            }
            tqu = std::move(m_queue); // 【一次性拿走所有任务】
            m_notfull.notify_all();
            return 0;
        }
        // 立即停止:直接置位标记,唤醒所有线程
        void stop()
        {
            {
                std::unique_lock<std::mutex> locker(m_mutex);
                m_needstop = true;
            }
            // 锁外唤醒!性能优化点
            m_notempty.notify_all();
            m_notfull.notify_all();
        }
        // 等待队空停止:处理完所有任务再停止(业务最常用)
        void waitqueueemptystop()
        {
            std::unique_lock<std::mutex> locker(m_mutex);
            // 等待队列所有任务消费完毕
            while (!isempty())
            {
                m_waitstop.wait_for(locker, std::chrono::milliseconds(m_waittime));
            }
            m_needstop = true;
            m_notfull.notify_all();
            m_notempty.notify_all();
        }
        bool empty() const
        {
            std::unique_lock<std::mutex> locker(m_mutex);
            return m_queue.empty();
        }
        bool full() const
        {
            std::unique_lock<std::mutex> locker(m_mutex);
            return m_queue.size() >= m_maxsize;
        }
        size_t size() const
        {
            std::unique_lock<std::mutex> locker(m_mutex);
            return m_queue.size();
        }
        size_t count() const
        {
            return m_queue.size();
        }
    };
} // namespace tulun
#endif

关键设计点

  • 双条件变量m_notempty 供消费者(线程池工作线程)等待,m_notfull 供生产者(任务提交线程)等待,减少无效唤醒;
  • 超时等待wait_for 替代无限等待,避免线程永久阻塞;
  • 移动语义put(t &&task) 支持右值引用,减少任务拷贝开销;
  • 异常安全:通过 unique_lock 管理锁,保证异常时锁自动释放。

2.2 缓存线程池核心(cachedthreadpool)

线程池的核心逻辑集中在线程管理任务调度,主要包含以下模块:

2.2.1 核心成员变量

class cachedthreadpool {
    public:
        using task = std::function<void(void)>;
    private:
        // static const int keepalivetime = 60; // s;
        static int keepalivetime;
        std::unordered_map<std::thread::id, std::shared_ptr<std::thread>> m_threadgroup;// 线程管理表
        int m_corethreadsize = 4; // 核心线程(永远不死)
        int m_maxthreadsize = std::thread::hardware_concurrency();// 最大线程数
        mutable std::mutex m_mutex;
        std::condition_variable m_threadexit;
        std::atomic<int> m_idlethreadsize = 0;// 空闲线程数量
        std::atomic<int> m_curthreadsize = 0;// 当前总线程数
        tulun::syncqueue<task> m_queue; // 任务队列
        std::atomic<bool> m_running = false; // true;// 运行标记
        std::once_flag m_flag;
};

2.2.2cachedthreadpool.hpp

#include "syncqueue_1.hpp"
#include <functional>
#include <map>
#include <unordered_map>
#include <thread>
#include <memory>
#include <mutex>
#include <condition_variable>
#include <atomic>
#include <future>
using namespace std;
#ifndef cached_thread_pool_hpp
#define cached_thread_pool_hpp
namespace tulun
{
    class cachedthreadpool
    {
    public:
        using task = std::function<void(void)>;
    private:
        // static const int keepalivetime = 60; // s;
        static int keepalivetime;
        std::unordered_map<std::thread::id, std::shared_ptr<std::thread>> m_threadgroup;// 线程管理表
        int m_corethreadsize = 4; // 核心线程(永远不死)
        int m_maxthreadsize = std::thread::hardware_concurrency();// 最大线程数
        mutable std::mutex m_mutex;
        std::condition_variable m_threadexit;
        std::atomic<int> m_idlethreadsize = 0;// 空闲线程数量
        std::atomic<int> m_curthreadsize = 0;// 当前总线程数
        tulun::syncqueue<task> m_queue; // 任务队列
        std::atomic<bool> m_running = false; // true;// 运行标记
        std::once_flag m_flag;
        void start(int numthreads);
        void runinthread();
        void stopthreadgroup();
        void newthread();
    public:
        cachedthreadpool(int initnumthreads = 2, int taskqueuesize = maxtaskcount);
        ~cachedthreadpool();
        void stop();
        void addtask(task &&task);
        void addtask(const task &task);
        void printinfo() const
        {
            std::lock_guard<std::mutex> locker(m_mutex);
            cout << "m_core: " << m_corethreadsize << endl;
            cout << "m_idle: " << m_idlethreadsize << endl;
            cout << "m_cur: " << m_curthreadsize << endl;
            cout << "m_max: " << m_maxthreadsize << endl;
            cout<<"-------------------------------"<<endl;
        }
        template <class func, class... args>
        auto submit(func &&func, args &&...args)
        {
            // typedef decltype(func(args...)) rettype;
            // using rettype = decltype(func(args...));
            // std::packaged_task<rettype()> task(
            //     std::bind(
            //         std::forward<func>(func),
            //         std::forward<args>(args)...)
            //);
            // 正确推导返回值(支持成员函数)
            using rettype = decltype(std::invoke(std::forward<func>(func), std::forward<args>(args)...));
            // 封装任务
            auto task = std::make_shared<std::packaged_task<rettype()>>(
                [func = std::forward<func>(func), ... args = std::forward<args>(args)]() mutable
                {
                    return std::invoke(func, args...);
                });
            std::future<rettype> result = task->get_future();
            if (m_queue.put([task]() -> void
                            { (*task)(); }) != 0)
            {
                log_error << "add task run task";
                (*task)();
            }
            newthread();
            return result;
        }
        int getthreadnum() const;
    };
}
#endif

2.2.3线程池初始化(start)

初始化时创建核心线程,作为常驻线程处理任务:

void cachedthreadpool::start(int numthreads)
    {
        m_running = true;
        m_curthreadsize = numthreads;
        // 创建核心线程
        for (int i = 0; i < numthreads; ++i)
        {
            auto tha = std::make_shared<std::thread>(&cachedthreadpool::runinthread, this);
            std::thread::id tid = tha->get_id();
            m_threadgroup.emplace(tid, tha);
            // 初始时所有线程都处于空闲状态(m_idlethreadsize 增加)。
            ++m_idlethreadsize;
        }
    }

2.2.4 工作线程逻辑(runinthread)

工作线程的核心逻辑是 “循环获取任务执行,空闲超时则回收”:

int cachedthreadpool::keepalivetime = 60;
void cachedthreadpool::runinthread()
    {
        auto tid = std::this_thread::get_id();
        auto starttime = std::chrono::high_resolution_clock().now();
        while (m_running)
        {
            task task;
            if (m_queue.empty())
            {
                auto now = std::chrono::high_resolution_clock().now();
                auto intervaltime =
                    std::chrono::duration_cast<std::chrono::seconds>(now - starttime).count();
                std::lock_guard<std::mutex> locker(m_mutex);
                if (intervaltime >= keepalivetime && m_curthreadsize > m_corethreadsize)
                {
                    // m_threadgroup.find(tid)->second->join();// error;
                    // 超时且当前线程数超过核心数 -> 该线程退出
                    m_threadgroup.find(tid)->second->detach();
                    // detach 后线程对象仍然在 m_threadgroup 中
                    m_threadgroup.erase(tid);
                    m_curthreadsize--;
                    m_idlethreadsize--;
                    // m_threadexit.notify_all();//????需要吗
                    return;
                }
            }
            // 当队列空且未停止时,take会阻塞或超时返回非
            // 返回值:0成功,1超时无任务,2停止
            if (m_queue.take(task) != 0)
            {
                continue;
            }
            if (m_running && task)
            {
                m_idlethreadsize--; // 即将执行任务,空闲数减1
                task();             // 执行任务
                m_idlethreadsize++; // 执行完毕,空闲数加1
                // 重置空闲计时起点(刚执行完任务,认为现在开始进入空闲期)
                starttime = std::chrono::high_resolution_clock().now();
            }
        }
    }

2.2.5 动态创建线程(newthread)

当空闲线程不足且未达最大线程数时,创建新线程:

 // 扩容
    void cachedthreadpool::newthread()
    {
        std::lock_guard<std::mutex> locker(m_mutex);
        if (m_idlethreadsize <= 0 && m_curthreadsize < m_maxthreadsize)
        {
            auto tha = std::make_shared<std::thread>(&cachedthreadpool::runinthread, this);
            std::thread::id tid = tha->get_id();
            m_threadgroup.emplace(tid, tha);
            m_idlethreadsize++;
            m_curthreadsize++;
        }
    }

2.2.6 任务提交接口

支持两种任务提交方式:普通任务(无返回值)和异步任务(带返回值)。

普通任务提交

void cachedthreadpool::addtask(task &&task)
    {
        if (m_queue.put(std::forward<task>(task)) != 0)
        {
            log_info << "task()";
            task();
        }
        newthread(); // 尝试创建新线程
    }
    void cachedthreadpool::addtask(const task &task)
    {
        if (m_queue.put(task) != 0)
        {
            log_info << "task()";
            task();
        }
        newthread();
    }

异步任务提交(带返回值):利用 packaged_taskfuture 实现异步结果获取:

template <class func, class... args>
        auto submit(func &&func, args &&...args)
        {
            // 正确推导返回值(支持成员函数)
            using rettype = decltype(std::invoke(std::forward<func>(func), std::forward<args>(args)...));
            // 封装任务
            auto task = std::make_shared<std::packaged_task<rettype()>>(
                [func = std::forward<func>(func), ... args = std::forward<args>(args)]() mutable
                {
                    return std::invoke(func, args...);
                });
            std::future<rettype> result = task->get_future();
            if (m_queue.put([task]() -> void
                            { (*task)(); }) != 0)
            {
                log_error << "add task run task";
                (*task)();
            }
            newthread();
            return result;
        }

2.2.7 优雅停止(stopthreadgroup)

停止线程池时,需等待所有任务执行完毕,再回收所有线程:

void cachedthreadpool::stopthreadgroup()
    {
        // 等待队列消费完毕,然后设置停止标志
        m_queue.waitqueueemptystop();
        m_corethreadsize = 0;
        keepalivetime = 0;// 强制回收所有空闲线程
        std::unique_lock<std::mutex> locker(m_mutex);
        while (!m_threadgroup.empty())
        {
            m_threadexit.wait_for(locker, std::chrono::milliseconds(100));
        }
        m_running = false;
    }
void cachedthreadpool::stop()
    {
        std::call_once(m_flag, std::bind(&cachedthreadpool::stopthreadgroup, this));
    }

2.2.8 构造+析构

cachedthreadpool::cachedthreadpool(int initnumthreads, int taskqueuesize)
        : m_corethreadsize(initnumthreads),
          // m_idlethreadsize(0),
          // m_maxthreadsize(0),
          // m_curthreadsize(0),
          m_queue(taskqueuesize)
    // m_running(false)
    {
        start(initnumthreads);
    }
 cachedthreadpool::~cachedthreadpool()
    {
        if (m_running)
        {
            stop();
        }
    }

三、缓存线程池 vs 固定线程池:核心特性对比

特性fixedthreadpoolcachedthreadpool
线程复用支持复用,但无法动态创建新线程优先复用空闲线程,无空闲线程时动态创建新线程
池大小固定数量(创建时指定)可增长,最大上限为 integer.max_value(或自定义上限)
队列大小无限制无限制
超时机制无空闲超时,线程常驻默认空闲线程存活 60 秒,超时自动回收
适用场景稳定高负载、cpu 密集型任务(避免频繁线程切换)大量短期异步任务、低负载波动场景
线程生命周期线程池销毁前不自动销毁空闲超时自动终止,避免资源浪费

从对比中可以看出:

  • fixedthreadpool 适合稳定的 cpu 密集型任务,避免线程频繁创建 / 销毁带来的开销;
  • cachedthreadpool 适合短期、并发波动大的 io 密集型任务,通过动态扩缩容平衡性能与资源消耗。

四、使用场景与最佳实践

4.1 缓存线程池的适用场景

结合特性,缓存线程池最适合以下场景:

  1. 大量短期任务:适合处理大量短期任务,当任务到来时尽可能创建新线程执行,空闲线程可复用,避免频繁创建 / 销毁线程的额外开销;
  2. 任务响应快速:适合需要快速响应的任务,可根据任务量快速创建 / 启动新线程,减少任务等待时间;
  3. 无需限制线程数量:适合任务到来时不限制线程数量的场景,只要内存充足,可动态创建新线程;
  4. 短期任务高并发:适合处理高并发的短期任务,任务完成后线程池保留空闲线程,为下一批任务做准备。

4.2 最佳实践与避坑指南

缓存线程池并非 “万能方案”,高负载场景下存在明显风险,因此工程实践中需注意以下几点:

  1. 警惕无界队列风险:无界任务队列可能导致内存溢出、任务延迟过高,建议设置有界队列;
  2. 控制最大线程数:默认无上限的线程创建可能导致系统资源耗尽,需自定义最大线程数;
  3. 避免长时间阻塞任务:缓存线程池不适合执行长时间任务,否则会导致后续任务堆积、线程数持续膨胀;
  4. 推荐使用 threadpoolexecutor:java/c++ 中可直接使用 threadpoolexecutor(或其 c++ 实现),通过自定义核心线程数、最大线程数、队列大小、拒绝策略实现细粒度控制;
  5. 扩展钩子函数:可重载 beforeexecute/afterexecute 钩子函数,实现任务执行前后的自定义操作(如日志、监控);
  6. 线程工厂定制:通过自定义 threadfactory 为线程命名、设置守护线程属性,便于问题排查;
  7. 动态调整池大小:可实现动态线程池,运行时根据任务量、cpu 使用率调整核心线程数与最大线程数。

五、缓存线程池的使用示例

以下示例展示了如何使用缓存线程池处理大规模任务(随机数生成):

#include <random>
#include <iostream>
using namespace std;
#include "timestamp.hpp"
#include "logger.hpp"
#include "cachedthreadpool.hpp"
static const size_t row = 10000;
static const size_t col = 100000;
std::vector<std::vector<int>> iveca, ivecb, ivecc, ivecd;
void randinit(std::vector<int> &ivec)
{
    std::random_device rd;                             // 真随机种子源
    std::mt19937 gen(rd());                            // 随机数引擎
    std::uniform_int_distribution<int> dis(0, 100000); // 分布范围 [1, 100]
    // int random_num = dis(gen);
    // ivec.reserve(col);
    for (int i = 0; i < col; ++i)
    {
        // ivec.push_back(rand() % 10000);
        ivec.push_back(dis(gen));
    }
}
void sortvec(std::vector<int> &ivec)
{
    std::sort(ivec.begin(), ivec.end());
}
void savefile(std::vector<int> &ivec, const std::string &filename)
{
    file *pf = fopen(filename.c_str(), "a");
    if (nullptr == pf)
    {
        log_fatal << "fopen fail \n";
        exit(exit_failure);
    }
    for (int i = 0; i < col; ++i)
    {
        fprintf(pf, "%d ", ivec[i]);
    }
    fprintf(pf, "\n---------------------\n");
    fclose(pf);
    pf = nullptr;
}
void test_funb()
{
    srand(time(nullptr));
    cout << "4 线程测试...." << endl;
    tulun::timestamp start, end;
    start = tulun::timestamp::now();
    {
        ivecb.resize(row);
        tulun::cachedthreadpool mypool(4, 500);
        for (int i = 0; i < row; ++i)
        {
            ivecb[i].reserve(col);
            // randinit(ivecb[i]);
            mypool.addtask(std::bind(randinit, std::ref(ivecb[i])));
            if ((i + 1) % 5000 == 0)
            {
                mypool.printinfo();
            }
        }
    }
    end = tulun::timestamp::now();
    cout << "randinit: " << (tulun::diffmicro(end, start)) / 1000000 << "." << (tulun::diffmicro(end, start)) % 1000000 << endl;
    start = tulun::timestamp::now();
    {
        tulun::cachedthreadpool mypool(4, 500);
        for (int i = 0; i < row; ++i)
        {
            // sortvec(ivecb[i]);
            mypool.addtask(std::bind(sortvec, std::ref(ivecb[i])));
            if ((i + 1) % 5000 == 0)
            {
                mypool.printinfo();
            }
        }
    }
    end = tulun::timestamp::now();
    cout << "sortvec : " << (tulun::diffmicro(end, start)) / 1000000 << "." << (tulun::diffmicro(end, start)) % 1000000 << endl;
    start = tulun::timestamp::now();
    {
        tulun::cachedthreadpool mypool(4, 500);
        for (int i = 0; i < row; ++i)
        {
            // savefile(ivecb[i], "iveca.txt");
            mypool.addtask(std::bind(savefile, std::ref(ivecb[i]), std::string("ivecb.txt")));
            if ((i + 1) % 5000 == 0)
            {
                mypool.printinfo();
            }
        }
    }
    end = tulun::timestamp::now();
    cout << "savefile: " << (tulun::diffmicro(end, start)) / 1000000 << "." << (tulun::diffmicro(end, start)) % 1000000 << endl;
    return;
}
void funa()
{
    for (int i = 0; i < 1000; ++i)
        ;
    std::this_thread::sleep_for(std::chrono::milliseconds(100));
}
void funb()
{
    for (int i = 0; i < 100; ++i)
        ;
    std::this_thread::sleep_for(std::chrono::milliseconds(rand() % 100));
}
void test_func()
{
    {
        tulun::cachedthreadpool mypool(4, 500);
        for (int i = 0; i < 1000; ++i)
        {
            mypool.addtask(funa);
            if ((i + 1) % 100 == 0)
            {
                mypool.printinfo();
            }
        }
        cout << "###############################" << endl;
        for (int i = 0; i < 1000; ++i)
        {
            mypool.addtask(funb);
            if ((i + 1) % 10 == 0)
            {
                mypool.printinfo();
            }
        }
        std::this_thread::sleep_for(std::chrono::seconds(1));
        mypool.printinfo();
        std::this_thread::sleep_for(std::chrono::seconds(1));
        mypool.printinfo();
        std::this_thread::sleep_for(std::chrono::seconds(1));
        mypool.printinfo();
        std::this_thread::sleep_for(std::chrono::seconds(1));
        mypool.printinfo();
        std::this_thread::sleep_for(std::chrono::seconds(1));
        mypool.printinfo();
        std::this_thread::sleep_for(std::chrono::seconds(1));
        mypool.printinfo();
        std::this_thread::sleep_for(std::chrono::seconds(1));
        mypool.printinfo();
        std::this_thread::sleep_for(std::chrono::seconds(1));
        mypool.printinfo();
        std::this_thread::sleep_for(std::chrono::seconds(1));
        mypool.printinfo();
    }
}
int main()
{
    tulun::logger::setloglevel(tulun::log_level::info);
    //test_funb();
    test_func();
    return 0;
}

六、核心设计亮点与优化方向

6.1 设计亮点

  • 原子变量保证线程安全m_idlethreadsizem_curthreadsize 等使用 std::atomic,避免锁竞争;
  • 超时机制避免永久阻塞:任务队列的 wait_for 和线程回收的超时判断,提升系统鲁棒性;
  • 移动语义减少拷贝:任务提交支持右值引用,降低大任务的拷贝开销;
  • 降级策略:任务队列满时,直接在提交线程执行任务,避免任务丢失;
  • 异步任务支持:通过 packaged_taskfuture 实现带返回值的任务提交。

6.2 可优化方向

  • 线程回收机制:当前使用 detach 回收线程,可改为 join 并结合线程池销毁逻辑,更安全;
  • 任务优先级:扩展任务队列支持优先级,优先执行高优先级任务;
  • 线程局部存储:为工作线程添加 tls(线程局部存储),减少线程间资源竞争;
  • 监控与统计:增加任务执行耗时、线程创建 / 回收次数等统计指标,便于性能调优;
  • 异常捕获:工作线程执行任务时捕获异常,避免单个任务崩溃导致线程退出。

七、总结

缓存线程池是高并发场景下的高效线程管理方案,其核心价值在于用动态扩缩容平衡性能与资源消耗

  • 用线程安全的任务队列解耦任务提交与执行;
  • 核心线程常驻,临时线程按需创建、超时回收;
  • 原子变量和条件变量保证多线程下的状态同步;
  • 降级策略和超时机制提升系统鲁棒性。

但缓存线程池并非 “银弹”,在高负载、长时间任务场景下需谨慎使用,建议结合threadpoolexecutor 的设计思想,通过自定义参数实现更可控的线程池。

到此这篇关于c++ 缓存线程池cachedthreadpool原理、实现与对比解析的文章就介绍到这了,更多相关c++ 缓存线程池cachedthreadpool内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!

(0)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2026  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com