码农知识堂 - 1000bd
  •   Python
  •   PHP
  •   JS/TS
  •   JAVA
  •   C/C++
  •   C#
  •   GO
  •   Kotlin
  •   Swift
  • CPP线程管理类实现


     一个线程管理模块应该包含Task(任务类)、Thread(线程类)、线程管理类(ThreadManager)。

    1. #pragma once
    2. #include
    3. #include
    4. #include
    5. #include
    6. #include
    7. #include
    8. #include
    9. typedef std::function<void(void*)> ThreadTaskFun;
    10. // 任务类
    11. class Task {
    12. public:
    13. Task(ThreadTaskFun, void* param = nullptr) : func_(std::move(func)), taskParams(param){}
    14. Task() {}
    15. void execute() {
    16. if (func_) {
    17. func_(taskParams);
    18. }
    19. }
    20. private:
    21. std::function<void(void*)> func_;
    22. void* taskParams;
    23. };
    24. // 线程类
    25. class Thread {
    26. public:
    27. Thread() : thread_(), active_(false) {}
    28. void start() {
    29. active_ = true;
    30. thread_ = std::thread([this]() {
    31. while (active_) {
    32. Task task;
    33. {
    34. std::unique_lock lock(mutex_);
    35. // 等待任务队列不为空
    36. condition_.wait(lock, [this]() { return !tasks_.empty() || !active_; });
    37. if (!active_) {
    38. break;
    39. }
    40. task = std::move(tasks_.front());
    41. tasks_.pop();
    42. }
    43. task.execute();
    44. }
    45. });
    46. }
    47. void stop() {
    48. if (active_) {
    49. active_ = false;
    50. condition_.notify_one();
    51. if (thread_.joinable()) {
    52. thread_.join();
    53. }
    54. }
    55. }
    56. void addTask(Task task) {
    57. std::lock_guard lock(mutex_);
    58. tasks_.push(std::move(task));
    59. condition_.notify_one();
    60. }
    61. private:
    62. std::thread thread_;
    63. std::queue tasks_;
    64. std::mutex mutex_;
    65. std::condition_variable condition_;
    66. bool active_;
    67. };
    68. // 线程管理类
    69. class ThreadManager {
    70. public:
    71. ThreadManager(int num_threads) {
    72. for (int i = 0; i < num_threads; ++i) {
    73. threads_.emplace_back(std::make_unique());
    74. }
    75. }
    76. ~ThreadManager()
    77. {
    78. stopThreads();
    79. }
    80. void startThreads() {
    81. for (auto& thread : threads_) {
    82. thread->start();
    83. }
    84. }
    85. void stopThreads() {
    86. for (auto& thread : threads_) {
    87. thread->stop();
    88. }
    89. }
    90. void addTask(Task task) {
    91. if (index_ >= threads_.size()) {
    92. index_ = 0; // 循环使用线程
    93. }
    94. threads_[index_]->addTask(std::move(task));
    95. index_++;
    96. }
    97. private:
    98. std::vector> threads_;
    99. int index_ = 0;
    100. };

    Demo

    1. #include "threadpool.h"
    2. class Resources
    3. {
    4. public:
    5. Resources()
    6. {
    7. resourcesThreadFun = std::bind(&Resources::exampleTaskFunction, this, std::placeholders::_1);
    8. }
    9. void exampleTaskFunction(void* param) {
    10. int index = 0;
    11. std::cout << "Executing task " << index << " in thread: " << std::this_thread::get_id() << std::endl;
    12. }
    13. ThreadTaskFun resourcesThreadFun;
    14. };
    15. int main() {
    16. ThreadManager manager(4); // 创建4个线程
    17. manager.startThreads();
    18. Resources* pResource = new Resources();
    19. // 添加10个示例任务
    20. for (int i = 0; i < 100; ++i) {
    21. Task task(pResource->resourcesThreadFun);
    22. manager.addTask(std::move(task));
    23. }
    24. std::cout << "main thread over!" << std::endl;
    25. return 0;
    26. }

  • 相关阅读:
    【Linux系统编程:信号】产生信号 | 阻塞信号 | 处理信号 | 可重入函数
    有哪些设计原则
    计算机毕业设计springboot健康管理系统1ii1u源码+系统+程序+lw文档+部署
    Redis模块五:持久化
    【MySQL】多表查询
    Mysql进阶优化篇01——四万字详解数据库性能分析工具(深入、全面、详细,收藏备用)
    STM32 与 ARM 的联系
    慢慢欣赏linux 进程unattended-upgr CPU占用率过高定位
    有 3 个候选人,每个选民只能投票选一人,要求编一个统计选票的程序,先后输入被选人的名字,最后输出各人得票结果
    字节跳动技术面都过了,结果还是被刷了,问HR原因竟是。。。
  • 原文地址:https://blog.csdn.net/qianlixiaomage/article/details/138169573
  • 最新文章
  • 攻防演习之三天拿下官网站群
    数据安全治理学习——前期安全规划和安全管理体系建设
    企业安全 | 企业内一次钓鱼演练准备过程
    内网渗透测试 | Kerberos协议及其部分攻击手法
    0day的产生 | 不懂代码的"代码审计"
    安装scrcpy-client模块av模块异常,环境问题解决方案
    leetcode hot100【LeetCode 279. 完全平方数】java实现
    OpenWrt下安装Mosquitto
    AnatoMask论文汇总
    【AI日记】24.11.01 LangChain、openai api和github copilot
  • 热门文章
  • 十款代码表白小特效 一个比一个浪漫 赶紧收藏起来吧!!!
    奉劝各位学弟学妹们,该打造你的技术影响力了!
    五年了,我在 CSDN 的两个一百万。
    Java俄罗斯方块,老程序员花了一个周末,连接中学年代!
    面试官都震惊,你这网络基础可以啊!
    你真的会用百度吗?我不信 — 那些不为人知的搜索引擎语法
    心情不好的时候,用 Python 画棵樱花树送给自己吧
    通宵一晚做出来的一款类似CS的第一人称射击游戏Demo!原来做游戏也不是很难,连憨憨学妹都学会了!
    13 万字 C 语言从入门到精通保姆级教程2021 年版
    10行代码集2000张美女图,Python爬虫120例,再上征途
Copyright © 2022 侵权请联系2656653265@qq.com    京ICP备2022015340号-1
正则表达式工具 cron表达式工具 密码生成工具

京公网安备 11010502049817号