线程池详解(c++手撕线程池)

线程池是管理线程的容器,核心作用是复用线程、控制并发数、降低资源消耗,是并发编程中优化性能的常用工具。

代码仓库: Thread_pool: 线程池是管理线程的容器,核心作用是复用线程、控制并发数、降低资源消耗,是并发编程中优化性能的常用工具。

核心思路 :

  • 提前创建出一批线程,避免线程频繁创建/销毁的开销。
  • 把任务储存再任务队列中,线程不断地从任务队列取任务执行,队列为空时进入休眠
  • 提供添加任务接口,隐藏了执行任务地细节。
  • 使用条件变量和CAS锁把对线程地唤醒和对任务队列地操作解耦,避免线程无意义地休眠。

核心成员:

  • 工作线程 : 提前创建地一批线程 。
  • 任务队列 : 存储任务

使用方法:

1.把 ThreadPool.h 文件加入项目中
2.创建 Thread_pool 对象,推荐使用智能指针
c++ 复制代码
    std::unique_ptr<Thread_pool> thread_pool = std::make_unique<Thread_pool>();
3.初始化工作线程 参数为线程数 默认为4线程
c++ 复制代码
    thread_pool->start_work();
4.添加任务
  • 参数

    • func 待执行的任务主体
    • args... 待执行任务 func 所需的参数列表,支持任意数量、任意类型的参数
  • 返回值

    • std::future 可异步获得运行结果 future.get() 阻塞等待任务完成并获取结果(若 func 返回 void,则 get() 仅等待任务完成),或通过 future.wait() 仅阻塞等待任务完成,不获取结果。
c++ 复制代码
    auto add = [](int a, int b) {
        return a + b;
        };
    auto fut =  thread_pool->submit(add, 1, 2);
    std::cout << fut.get() << std::endl;
5.停止线程池
c++ 复制代码
thread_pool->stop_work();
6.阻塞主线程
c++ 复制代码
thread_pool->join();

简单示例:

复制代码
#include "ThreadPool.h"
#include <iostream>
#include <vector>
std::mutex mtx;
int main() {
    std::unique_ptr<Thread_pool> thread_pool = std::make_unique<Thread_pool>();
    thread_pool->start_work();
    auto print_thread = []() {
        std::unique_lock<std::mutex>lock(mtx);
        std::cout << std::this_thread::get_id() << std::endl;
        };
    for (int i = 0; i < 100; ++i) {
        thread_pool->submit(print_thread);
    }
    thread_pool->stop_work();
    thread_pool->join();
    return 0;
}

test压力测试结果:

相关推荐
端平入洛18 小时前
delete又未完全delete
c++
端平入洛2 天前
auto有时不auto
c++
哇哈哈20213 天前
信号量和信号
linux·c++
多恩Stone3 天前
【C++入门扫盲1】C++ 与 Python:类型、编译器/解释器与 CPU 的关系
开发语言·c++·人工智能·python·算法·3d·aigc
蜡笔小马3 天前
21.Boost.Geometry disjoint、distance、envelope、equals、expand和for_each算法接口详解
c++·算法·boost
超级大福宝3 天前
N皇后问题:经典回溯算法的一些分析
数据结构·c++·算法·leetcode
weiabc3 天前
printf(“%lf“, ys) 和 cout << ys 输出的浮点数格式存在细微差异
数据结构·c++·算法
问好眼3 天前
《算法竞赛进阶指南》0x01 位运算-3.64位整数乘法
c++·算法·位运算·信息学奥赛
yyjtx3 天前
DHU上机打卡D31
开发语言·c++·算法
czxyvX3 天前
020-C++之unordered容器
数据结构·c++