当前位置: 首页 > news >正文

简单的线程池示例

线程池可以有效地管理和重用线程资源,避免频繁创建和销毁线程带来的开销。以下是一个简单的线程池示例。

cpp
#include <iostream>
#include <vector>
#include <thread>
#include <queue>
#include <mutex>
#include <condition_variable>
#include <functional>class ThreadPool {
public:ThreadPool(size_t numThreads);~ThreadPool();void enqueue(std::function<void()> func);private:std::vector<std::thread> workers;std::queue<std::function<void()>> tasks;std::mutex queueMutex;std::condition_variable condition;bool stop;void worker();
};ThreadPool::ThreadPool(size_t numThreads) : stop(false) {for (size_t i = 0; i < numThreads; ++i) {workers.emplace_back([this] { this->worker(); });}
}ThreadPool::~ThreadPool() {{std::unique_lock<std::mutex> lock(queueMutex);stop = true;}condition.notify_all();for (std::thread &worker : workers) {worker.join();}
}void ThreadPool::enqueue(std::function<void()> func) {{std::unique_lock<std::mutex> lock(queueMutex);tasks.push(func);}condition.notify_one();
}void ThreadPool::worker() {while (true) {std::function<void()> task;{std::unique_lock<std::mutex> lock(queueMutex);condition.wait(lock, [this] { return this->stop || !this->tasks.empty(); });if (this->stop && this->tasks.empty()) return;task = std::move(this->tasks.front());this->tasks.pop();}task();}
}// 示例使用
void exampleTask(int n) {std::cout << "Task " << n << " is being processed by thread " << std::this_thread::get_id() << std::endl;std::this_thread::sleep_for(std::chrono::seconds(1));
}int main() {ThreadPool pool(4); // 创建具有4个线程的线程池for (int i = 0; i < 10; ++i) {pool.enqueue([i] { exampleTask(i); });}`在这里插入代码片`std::this_thread::sleep_for(std::chrono::seconds(5)); // 保证主线程等待足够长的时间让线程池处理完任务return 0;
}
http://www.lryc.cn/news/375608.html

相关文章:

  • IT入门知识第三部分《软件开发》(3/10)
  • 卫星通讯助力船舶可视化监控:EasyCVR视频汇聚系统新应用
  • gcn+tcn+transformer入侵检测
  • 【Python】 了解二分类:机器学习中的基础任务
  • 搭建PHP开发环境:Linux篇
  • ROS 自动驾驶多点巡航
  • SQL学习,大厂面试真题(1):观看各个视频的平均完播率
  • 2023年全国大学生数学建模竞赛C题蔬菜类商品的自动定价与补货决策(含word论文和源代码资源)
  • inpaint下载安装2024-inpaint软件安装包下载v5.0.6官网最新版附加详细安装步骤
  • 分享三个仓库
  • MacOS - 启动台多了个『卸载 Adobe Photoshop』
  • PHP 日期处理完全指南
  • KVB:怎么样选择最优交易周期?
  • 前端面试题日常练-day69 【面试题】
  • Java 解析xml文件-工具类
  • PyQt5学习系列之新项目创建并使用widget
  • mtk8675 安卓端assert函数的坑
  • 编程入门笔记:从基础到进阶的探索之旅
  • 小规模自建 Elasticsearch 的部署及优化
  • MySQL 示例数据库大全
  • VirtualBox、Centos7下安装docker后pull镜像问题、ftp上传文件问题
  • 链表 题目汇总
  • grafana连接influxdb2.x做数据大盘
  • Java证件识别中的身份证识别接口
  • 迷你小风扇哪个品牌好?迷你小风扇前十名公开揭晓!
  • MikroTik RouterOS 授权签名验证分析
  • C#开发-集合使用和技巧(六)特殊转换方法SelectMany的介绍和用法
  • 高考后的抉择:如何在心仪专业与知名学校之间做出选择?
  • 黄仁勋提到的机器人世界,还需要AI数据来“调教” | CVPR 2024
  • 语言中 函数用地址传参的好处