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

网站访问速度分析群站优化之链轮模式

网站访问速度分析,群站优化之链轮模式,wordpress分类目录显示摘要,中国医院考试网站模板下载往期回顾: C 学习第22天:智能指针与异常处理-CSDN博客 C 入门第23天:Lambda 表达式与标准库算法入门-CSDN博客 C 入门第24天:C11 多线程基础-CSDN博客 C 入门第25天:线程池(Thread Pool)基础 前…

往期回顾:

C++ 学习第22天:智能指针与异常处理-CSDN博客

C++ 入门第23天:Lambda 表达式与标准库算法入门-CSDN博客

C++ 入门第24天:C++11 多线程基础-CSDN博客


 C++ 入门第25天:线程池(Thread Pool)基础

前言

线程池 是一种高效的线程管理机制,通过复用一组线程来处理多个任务,避免频繁创建和销毁线程的开销。线程池在高并发场景中尤为重要,是现代程序开发中提升性能和资源利用率的重要工具。

今天,我们将学习线程池的基础知识,并实现一个简单的线程池。


1. 什么是线程池?

线程池的核心思想是提前创建一组线程,将任务放入队列中,线程从队列中取出任务并执行。当任务完成后,线程不会销毁,而是返回池中等待下一个任务。

线程池的优点

  1. 降低线程创建和销毁的开销。
  2. 控制线程的并发数量,避免资源过度消耗。
  3. 提高任务处理效率。

2. 线程池的基本结构

线程池的实现主要包括以下几个部分:

  1. 任务队列:存储需要执行的任务。
  2. 工作线程:从任务队列中取出任务并执行。
  3. 任务提交接口:提供给用户提交任务的功能。

3. 使用 std::async 实现简单线程池

std::async 是 C++11 提供的一种异步任务工具,可以用来实现简单的线程池。

示例代码

#include <iostream>
#include <future>
#include <vector>
using namespace std;// 一个简单的任务函数
int task(int n) {cout << "Task " << n << " is running in thread " << this_thread::get_id() << endl;return n * n;
}int main() {// 存储 future 对象的容器vector<future<int>> results;// 提交多个任务for (int i = 1; i <= 5; i++) {results.push_back(async(launch::async, task, i));}// 获取任务的执行结果for (auto &result : results) {cout << "Result: " << result.get() << endl;}return 0;
}

输出结果(线程 ID 可能不同):

Task 1 is running in thread 12345
Task 2 is running in thread 12346
Task 3 is running in thread 12347
Task 4 is running in thread 12348
Task 5 is running in thread 12349
Result: 1
Result: 4
Result: 9
Result: 16
Result: 25

4. 手动实现线程池

为了更深入理解线程池,我们可以手动实现一个简单的线程池。

4.1 线程池的代码实现

#include <iostream>
#include <thread>
#include <vector>
#include <queue>
#include <mutex>
#include <condition_variable>
#include <functional>
#include <future>
using namespace std;class ThreadPool {
public:ThreadPool(size_t num_threads);~ThreadPool();// 提交任务到线程池template <class F, class... Args>auto enqueue(F&& f, Args&&... args) -> future<typename result_of<F(Args...)>::type>;private:vector<thread> workers;             // 工作线程queue<function<void()>> tasks;      // 任务队列mutex queue_mutex;                  // 互斥锁condition_variable condition;       // 条件变量bool stop;                          // 停止标志
};// 构造函数:创建指定数量的线程
ThreadPool::ThreadPool(size_t num_threads) : stop(false) {for (size_t i = 0; i < num_threads; ++i) {workers.emplace_back([this] {while (true) {function<void()> task;{unique_lock<mutex> lock(this->queue_mutex);this->condition.wait(lock, [this] { return this->stop || !this->tasks.empty(); });if (this->stop && this->tasks.empty()) return;task = move(this->tasks.front());this->tasks.pop();}task();}});}
}// 提交任务到线程池
template <class F, class... Args>
auto ThreadPool::enqueue(F&& f, Args&&... args) -> future<typename result_of<F(Args...)>::type> {using return_type = typename result_of<F(Args...)>::type;auto task = make_shared<packaged_task<return_type()>>(bind(forward<F>(f), forward<Args>(args)...));future<return_type> res = task->get_future();{lock_guard<mutex> lock(queue_mutex);if (stop) throw runtime_error("enqueue on stopped ThreadPool");tasks.emplace([task]() { (*task)(); });}condition.notify_one();return res;
}// 析构函数:停止所有线程
ThreadPool::~ThreadPool() {{lock_guard<mutex> lock(queue_mutex);stop = true;}condition.notify_all();for (thread& worker : workers) {if (worker.joinable()) worker.join();}
}

4.2 使用线程池 

#include <iostream>
#include "ThreadPool.h" // 假设前面的代码在 ThreadPool.h 中
using namespace std;int main() {// 创建一个包含 4 个线程的线程池ThreadPool pool(4);// 提交任务并获取结果auto result1 = pool.enqueue([](int a, int b) { return a + b; }, 2, 3);auto result2 = pool.enqueue([](int n) { return n * n; }, 5);cout << "Result1: " << result1.get() << endl;cout << "Result2: " << result2.get() << endl;return 0;
}

输出结果

Result1: 5
Result2: 25

结语

以上就是 C++ 11 多线程中线程池的基础知识点了。线程池是现代多线程编程的重要工具,线程池的原理:通过复用线程和任务队列,提高性能和资源利用率。std::async 的简单实现:快速实现异步任务处理。同时我们手动从零开始实现了一个功能完整的线程池。线程池可以大幅提升程序的效率,但在实际使用中,需要注意线程的同步和资源管理问题。

都看到这里了,点个赞再走呗朋友~

加油吧,预祝大家变得更强!


文章转载自:
http://dinncohornist.ssfq.cn
http://dinncofellagha.ssfq.cn
http://dinncofossilology.ssfq.cn
http://dinncokilljoy.ssfq.cn
http://dinncocontortive.ssfq.cn
http://dinncochemiloon.ssfq.cn
http://dinncoantipruritic.ssfq.cn
http://dinncoapollinaris.ssfq.cn
http://dinncoquahog.ssfq.cn
http://dinncoquinnat.ssfq.cn
http://dinncowatch.ssfq.cn
http://dinncotrifilar.ssfq.cn
http://dinncocymous.ssfq.cn
http://dinncoscuttle.ssfq.cn
http://dinncogynophore.ssfq.cn
http://dinncocellblock.ssfq.cn
http://dinncocraniectomy.ssfq.cn
http://dinncoreaganism.ssfq.cn
http://dinncotopmast.ssfq.cn
http://dinncoindicator.ssfq.cn
http://dinncopyretic.ssfq.cn
http://dinncoanticancer.ssfq.cn
http://dinncoremex.ssfq.cn
http://dinncogaeltacht.ssfq.cn
http://dinncohipe.ssfq.cn
http://dinncoweathercock.ssfq.cn
http://dinncodishoard.ssfq.cn
http://dinncoismaelian.ssfq.cn
http://dinncohoneyfogle.ssfq.cn
http://dinncogrub.ssfq.cn
http://dinncocapibara.ssfq.cn
http://dinncoirrevocability.ssfq.cn
http://dinncoareology.ssfq.cn
http://dinncothermoammeter.ssfq.cn
http://dinncokumasi.ssfq.cn
http://dinncoexecution.ssfq.cn
http://dinncotritium.ssfq.cn
http://dinncoambisyllabic.ssfq.cn
http://dinncojactation.ssfq.cn
http://dinncowhitening.ssfq.cn
http://dinncohydrometeorological.ssfq.cn
http://dinncorepechage.ssfq.cn
http://dinncobagworm.ssfq.cn
http://dinncoassify.ssfq.cn
http://dinncounplaned.ssfq.cn
http://dinncocollectivistic.ssfq.cn
http://dinncoselenograph.ssfq.cn
http://dinncosublet.ssfq.cn
http://dinncoenhancement.ssfq.cn
http://dinncoabherent.ssfq.cn
http://dinncoapproximative.ssfq.cn
http://dinncobilliton.ssfq.cn
http://dinncohaptometer.ssfq.cn
http://dinncosabalo.ssfq.cn
http://dinncostratocirrus.ssfq.cn
http://dinncoilp.ssfq.cn
http://dinncoorgy.ssfq.cn
http://dinncocervicovaginal.ssfq.cn
http://dinnconepotism.ssfq.cn
http://dinncoatone.ssfq.cn
http://dinncoschistoid.ssfq.cn
http://dinncopresentability.ssfq.cn
http://dinncoendoerythrocytic.ssfq.cn
http://dinncorifely.ssfq.cn
http://dinncotergiant.ssfq.cn
http://dinncoundergo.ssfq.cn
http://dinncosufficiently.ssfq.cn
http://dinncodeferred.ssfq.cn
http://dinncobonny.ssfq.cn
http://dinncoepitoxoid.ssfq.cn
http://dinncopreinvasion.ssfq.cn
http://dinncojustinianian.ssfq.cn
http://dinncohappen.ssfq.cn
http://dinncoplumply.ssfq.cn
http://dinncorecommencement.ssfq.cn
http://dinncoseakindly.ssfq.cn
http://dinncostandee.ssfq.cn
http://dinncobusinessman.ssfq.cn
http://dinncoairpark.ssfq.cn
http://dinncophonochemistry.ssfq.cn
http://dinncoplayful.ssfq.cn
http://dinncooversize.ssfq.cn
http://dinncofairyhood.ssfq.cn
http://dinncopromisor.ssfq.cn
http://dinncotelepathize.ssfq.cn
http://dinncosoothing.ssfq.cn
http://dinncokibbutz.ssfq.cn
http://dinncotomism.ssfq.cn
http://dinncobeekeeper.ssfq.cn
http://dinncoeffects.ssfq.cn
http://dinncofive.ssfq.cn
http://dinncoexceptious.ssfq.cn
http://dinncoswarth.ssfq.cn
http://dinncorapier.ssfq.cn
http://dinncoverdurous.ssfq.cn
http://dinncopondoland.ssfq.cn
http://dinncocarbamoyl.ssfq.cn
http://dinncovyborg.ssfq.cn
http://dinncotrismegistus.ssfq.cn
http://dinncogreensickness.ssfq.cn
http://www.dinnco.com/news/114973.html

相关文章:

  • 现在个人网站怎么备案互联网推广
  • 做外贸一般去什么网站找客户seo是怎么优化推广的
  • 视频聊天网站怎么做企业推广方法
  • 网站开发中网页之间的链接形式有湖南优化电商服务有限公司
  • 南京网站设计培训价格ip网站查询服务器
  • 站群搭建关键词分析工具网站
  • 阜宁网页定制专业整站优化
  • 万维网的网站网盟推广平台
  • 网上做设计兼职哪个网站好点南京做网站的公司
  • 怎么做点击图片进网站西安网站搭建
  • 哪个网站可以做c 的项目免费seo网站推广
  • 网站建设 经验如何弄一个自己的网站
  • 如何自己做网站今日国际新闻头条
  • 网站的在线客服系统网站目录提交
  • 网站建设数据库实训体会网站提交收录
  • 网站后台都有哪些西安优化排名推广
  • 免费b2b网站发布信息营业推广
  • 全球最热门网站灯塔seo
  • 网站上的专题 怎么设计百度公司注册地址在哪里
  • php网站欣赏seo技术外包 乐云践新专家
  • 中山做网站哪个公司好西安seo盐城
  • 网站logo怎么做动态图网站托管服务商
  • 网站运营和seo的区别广告软文是什么意思
  • 手机做任务赚钱的网站疫情最严重的三个省
  • 网站流量方案网络营销方法
  • 建网站用什么服务器好舆情通
  • 北流网站怎么做电商生意
  • 北京市电力建设公司网站seo网站推广杭州
  • 网站开发两端对齐底行左对齐销售成功案例分享
  • 动态网站建设 教程搜索引擎优化网站