惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

雷峰网
雷峰网
Recorded Future
Recorded Future
B
Blog
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
博客园 - 聂微东
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
量子位
GbyAI
GbyAI
IT之家
IT之家
Microsoft Azure Blog
Microsoft Azure Blog
I
InfoQ
S
SegmentFault 最新的问题
T
Tailwind CSS Blog
有赞技术团队
有赞技术团队
M
MIT News - Artificial intelligence
罗磊的独立博客
MongoDB | Blog
MongoDB | Blog
The Cloudflare Blog
CTFtime.org: upcoming CTF events
CTFtime.org: upcoming CTF events
腾讯CDC
小众软件
小众软件
博客园 - 三生石上(FineUI控件)
aimingoo的专栏
aimingoo的专栏
博客园 - Franky
Martin Fowler
Martin Fowler
P
Proofpoint News Feed
月光博客
月光博客
博客园_首页
C
Check Point Blog
宝玉的分享
宝玉的分享
Security Archives - TechRepublic
Security Archives - TechRepublic
T
Tenable Blog
Vercel News
Vercel News
SecWiki News
SecWiki News
Security Latest
Security Latest
Microsoft Security Blog
Microsoft Security Blog
cs.CL updates on arXiv.org
cs.CL updates on arXiv.org
阮一峰的网络日志
阮一峰的网络日志
Hacker News - Newest:
Hacker News - Newest: "LLM"
Google Online Security Blog
Google Online Security Blog
N
News and Events Feed by Topic
Y
Y Combinator Blog
U
Unit 42
The Register - Security
The Register - Security
云风的 BLOG
云风的 BLOG
K
Kaspersky official blog
WordPress大学
WordPress大学
Blog — PlanetScale
Blog — PlanetScale
N
Netflix TechBlog - Medium
Jina AI
Jina AI

Shiroha白羽的博客

Golang 踩坑 —— interface 为参数的时候传 nil 指针 Codeforces Round 925 (Div. 3) Codeforces Round 924 (Div. 2) Codeforces Round 923 (Div. 3) Codeforces Round 922 (Div. 2) Codeforces Round 921 (Div. 2) Educational Codeforces Round 161 (Rated for Div. 2) Codeforces Round 920 (Div. 3) Codeforces Round 919 (Div. 2) Hello 2024 Good Bye 2023 Codeforces Round 918 (Div. 4) 个人备份的常用 macOS 清理命令 Codeforces Round 917 (Div. 2) Pinely Round 3 (Div. 1 + Div. 2) Educational Codeforces Round 160 (Rated for Div. 2) Codeforces Round 915 (Div. 2) Codeforces Round 914 (Div. 2) Codeforces Round 913 (Div. 3) Educational Codeforces Round 159 (Rated for Div. 2) Codeforces Round 912 (Div. 2) Codeforces Round 911 (Div. 2) CodeTON Round 7 (Div. 1 + Div. 2, Rated, Prizes!) Educational Codeforces Round 158 (Rated for Div. 2) Codeforces Round 910 (Div. 2) Codeforces Round 909 (Div. 3) Codeforces Round 908 (Div. 2) Educational Codeforces Round 157 (Rated for Div. 2) C++自定义的字面量 Codeforces Round 907 (Div. 2) Codeforces Round 916 (Div. 3) 关于 LRU map 的一些灵感 2023 杭州站 ICPC 现场赛 反复横跳的 Clang-Tidy(cert-dcl21-cpp) Codeforces Round 906 (Div. 2) 一段奇怪的 CPP 代码 Codeforces Round 905 (Div. 3) Codeforces Round 904 (Div. 2) Codeforces Round 903 (Div. 3) Educational Codeforces Round 156 (Rated for Div. 2) Codeforces Round 902 (Div. 2, based on COMPFEST 15 - Final Round) Codeforces Round 901 (Div. 2) Codeforces Round 900 (Div. 3) Codeforces Round 899 (Div. 2) Educational Codeforces Round#155 (Div. 2) Codeforces Round 898 (Div. 4) CodeTON Round 6 (Div. 2) Codeforces Round 897 (Div. 2) Codeforces Round 896 (Div. 2) Codeforces Round 887 (Div. 2) Codeforces Round 895 (Div. 3) 左值-右值-将亡值 blog.mauve.icu Pinely Round 2 (Div. 1 + Div. 2) Harbour.Space Scholarship Contest 2023-2024 (Div. 1 + Div. 2) Codeforces Round 894 (Div. 3) Codeforces Round 888 (Div. 3) Educational Codeforces Round#153 (Div. 2) Codeforces Round 893 (Div. 2) OTPAUTH,两步验证中的通用协议 Codeforces Round 892 (Div. 2) Codeforces Round 891 (Div. 3) Codeforces Round 890 (Div. 2) Educational Codeforces Round#152 (Div. 2) blog.mauve.icu Java Script 的 null 和 undefined 随想 记一次 SQL LEFT JOIN 没有得到预期结果的错误 Codeforces Round#789(Div. 2) GCC/G++ 预编译头性能优化 使用 Junit5 和 Mockito 实现 SpringBoot 的单元测试最优美的解决方案 centOS 防火墙 docker-compse 的问题 Codeforces Round#744 (Div. 3) 计算机图形学 Windows 通过网络访问 WSL2 原生 JavaScript 实现图片裁剪 面试复习(计算机图形学) 面试复习(算法) Codeforces Round#706(Div. 2)-Let's Go Hiking 面试复习(Java) 面试复习(Git) 面试复习(Linux) 面试复习(数据库) 面试复习(计算机网络) 面试复习(操作系统) 面试复习(C++) Codeforces Round#699 (Div. 2) 清理 WSL2 的磁盘占用 Codeforces Round#697 (Div. 3) Windows 下的 NTFS 驱动器索引 BUG 计算机网络复习 记一次 Navicat 连接 MySQL 一直报认证错误(Access denied) 计算机网络实验复习 WSL1 使用 Docker 一直无法启动 我的ACM脚印 2020牛客暑期多校训练营(第三场)D-Points Construction Problem——构造 2020牛客暑期多校训练营(第三场)E-Two Matchings——复杂思维与简单dp 2020牛客暑期多校训练营(第二场)I-Interval——最大流转对偶图求最短路 Educational Codeforces Round 80 D. Minimax Problem——二分+二进制处理 Codeforces Round 606 E. Two Fairs——图论 Codeforces Round 612 (Div. 2) C. Garland——DP
C++ 语言实现动态变化的线程池
Shiroha · 2021-10-13 · via Shiroha白羽的博客

线程池

Job

Job 作为任务的类型

1
2
3
4
5
6
7
8
class Job {
void *data;
function<void(void *data)> func;
public:
Job(void *data, function<void(void *data)> func);

void exec();
};

其中定义两个变量,data,和 func

func 用来保存需要调用的方法,当执行任务时,调用此函数即可。考虑到需要传递参数的可能,所以定义参数为一个指针,而另一个变量 data 则为需要传递给 func 的参数指针

函数的实现为

1
2
3
4
5
6
7
8
Job::Job(void *data, function<void(void *)> func) {
this->data = data;
this->func = move(func);
}

void Job::exec() {
func(data);
}

线程池核心代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
class ThreadPool {
private:
Mutex<map<pthread_t, thread *>> threadPool; // 线程池
Mutex<queue<Job *>> enqueue; // 任务队列
Mutex<vector<thread *>> deathThread; // 已经死亡的线程
Mutex<int> needKill; // 需要杀死的线程数量
condition_variable noTaskCv; // 无任务时的条件信号量
mutex noTaskCvMutex; // 无任务的条件信号量的锁
int maxCore; // 核心线程数
bool killed; // 已经终止了

Job *takeJob(); // 获取一个任务

virtual void addThread(); // 添加一个线程

void clean(); // 清理所有死亡的线程

public:
explicit ThreadPool(int core); // 构造函数

void submit(Job *job); // 提交任务,需要提交一个指针类型,且不需要主动 delete,当任务完成后,会被线程池 delete 掉

int getAccumulation(); // 获取当前堆积任务数量

void updateCore(int newCount); // 更新核心线程数,若增加则会新增线程,若减少则会在空闲时间关闭部分线程

void wait(); // 设定线程池为终止,不再可以提交任务,并等待所有任务完成

void close(); // 强制关闭线程池,不等待任务完成
};

  • 首先通过 init 函数初始化核心线程数
  • 通过 submit 的函数提交任务,必须是一个 job 指针,且必须是单独 new 出来的,线程池会自动清理已经完成的任务
  • 可以随时通过 getAccumulation 来获取到当前堆积的任务,使得可以手动调整线程池数量
  • 使用 upateCore 来调整核心线程数量
  • 建议通过 wait 来实现终止线程池

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
     ThreadPool::ThreadPool(int core) : maxCore(core), killed(false), needKill(0) {
    for (int i = 0; i < core; ++i) addThread();
    }

    Job *ThreadPool::takeJob() {
    Job *cur = nullptr;
    enqueue.run([&](queue<Job *> &q) {
    if (q.empty()) return;
    cur = q.front();
    q.pop();
    });
    return cur;
    }

    void ThreadPool::addThread() {
    auto work = [&]() {
    while (true) {
    Job *cur = takeJob();
    if (cur != nullptr) {
    cur->exec();
    delete cur;
    } else {
    bool dead = false;
    needKill.run([&](int &count) {
    if (count <= 0) return;
    dead = true;
    count--;
    });
    if (dead) break;

    clean();
    unique_lock<mutex> lk(noTaskCvMutex);
    noTaskCv.wait(lk);
    }
    }
    threadPool.run([&](map<pthread_t, thread *> &data) {
    auto iter = data.find(pthread_self());
    deathThread.run([&](vector<thread *> &data) {
    data.push_back(iter->second);
    });
    data.erase(iter);
    });
    };

    auto *newThread = new thread(work);
    threadPool.run([&](map<pthread_t, thread *> &data) {
    data.insert({newThread->native_handle(), newThread});
    });
    }

    void ThreadPool::clean() {
    if (deathThread.get().empty()) return;
    deathThread.run([&](vector<thread *> &data) {
    for (auto &item: data) delete item;
    });
    }

    void ThreadPool::submit(Job *job) {
    if (killed) return;
    enqueue.run([&](queue<Job *> &q) {
    q.push(job);
    noTaskCv.notify_one();
    });
    }

    int ThreadPool::getAccumulation() {
    return (int) enqueue.get().size();
    }

    void ThreadPool::updateCore(int newCount) {
    if (killed) return;
    needKill.run([&](int &cleaned) {
    if (newCount > this->maxCore)
    for (int i = this->maxCore; i < newCount; ++i)
    addThread();
    else {
    cleaned += this->maxCore - newCount;
    noTaskCv.notify_all();
    }
    });
    }

    void ThreadPool::wait() {
    updateCore(0);
    killed = true;
    map<pthread_t, thread *> tmp = threadPool.get();
    for (auto &item: tmp)
    item.second->join();
    }

    void ThreadPool::close() {
    killed = true;
    map<pthread_t, thread *> tmp = threadPool.get();
    for (auto &item: tmp) {
    pthread_kill(item.first, SIGKILL);
    delete item.second;
    }
    }

线程任务流程

  • 尝试获取一个任务
  • 若有任务
    • 执行任务
    • 删除任务
  • 若无任务
    • 检查是否有需要杀死的线程
    • 若有需要杀死的线程
      • 将当前线程添加进入已经结束线程组
      • 将当前线程从线程池中移除
    • 若无需要杀死的线程
      • 清理需要删除的任务
      • 进入等待状态