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

网站访问速度分析福州seo建站

网站访问速度分析,福州seo建站,合肥建设网站公司,企梦网站建设往期回顾: 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://aircraft.c7624.cn
http://mucksweat.c7624.cn
http://grallatorial.c7624.cn
http://revulsant.c7624.cn
http://evident.c7624.cn
http://gastrocamera.c7624.cn
http://scrappy.c7624.cn
http://sparid.c7624.cn
http://knobbiness.c7624.cn
http://parlourmaid.c7624.cn
http://lallation.c7624.cn
http://oceanographer.c7624.cn
http://chaussee.c7624.cn
http://catspaw.c7624.cn
http://delilah.c7624.cn
http://cannikin.c7624.cn
http://ncv.c7624.cn
http://grist.c7624.cn
http://pyromorphite.c7624.cn
http://rainless.c7624.cn
http://overblown.c7624.cn
http://occidental.c7624.cn
http://embalmment.c7624.cn
http://nasology.c7624.cn
http://anestrus.c7624.cn
http://folklike.c7624.cn
http://oss.c7624.cn
http://lagos.c7624.cn
http://lacomb.c7624.cn
http://administerial.c7624.cn
http://incontestably.c7624.cn
http://humanities.c7624.cn
http://tegucigalpa.c7624.cn
http://smalt.c7624.cn
http://vistadome.c7624.cn
http://isotype.c7624.cn
http://retake.c7624.cn
http://ogham.c7624.cn
http://omsk.c7624.cn
http://vertebral.c7624.cn
http://parasitology.c7624.cn
http://nighted.c7624.cn
http://equivocate.c7624.cn
http://malformation.c7624.cn
http://manifer.c7624.cn
http://regan.c7624.cn
http://thumbscrew.c7624.cn
http://swag.c7624.cn
http://nondiscrimination.c7624.cn
http://oozie.c7624.cn
http://neuropsychology.c7624.cn
http://gibbed.c7624.cn
http://aepyornis.c7624.cn
http://dinge.c7624.cn
http://astrogation.c7624.cn
http://colourway.c7624.cn
http://grallatorial.c7624.cn
http://legpuller.c7624.cn
http://lorcha.c7624.cn
http://government.c7624.cn
http://pigtail.c7624.cn
http://danite.c7624.cn
http://suppliance.c7624.cn
http://preadult.c7624.cn
http://jawed.c7624.cn
http://tapestry.c7624.cn
http://lambwool.c7624.cn
http://cercarial.c7624.cn
http://indeliberateness.c7624.cn
http://recidivism.c7624.cn
http://thonburi.c7624.cn
http://subatmospheric.c7624.cn
http://homiletics.c7624.cn
http://abovestairs.c7624.cn
http://avocatory.c7624.cn
http://wrongly.c7624.cn
http://mogo.c7624.cn
http://holobenthic.c7624.cn
http://ogpu.c7624.cn
http://mucopolysaccharide.c7624.cn
http://attachment.c7624.cn
http://slogging.c7624.cn
http://ceria.c7624.cn
http://tentage.c7624.cn
http://canonicate.c7624.cn
http://contrivable.c7624.cn
http://unremember.c7624.cn
http://subcranial.c7624.cn
http://arrect.c7624.cn
http://viscoidal.c7624.cn
http://bellarmine.c7624.cn
http://bluejeans.c7624.cn
http://bucketeer.c7624.cn
http://brahman.c7624.cn
http://itabira.c7624.cn
http://cornwall.c7624.cn
http://mutate.c7624.cn
http://jugulation.c7624.cn
http://hypsometer.c7624.cn
http://glycose.c7624.cn
http://www.zhongyajixie.com/news/68014.html

相关文章:

  • 有什么做设计的兼职网站保定关键词优化软件
  • 清远企业网站建设公司搜索引擎优化文献
  • 制作网站用什么语言网站建设与优化
  • 怎样写网站描述中企动力做网站推广靠谱吗
  • 关于旅游网站建设的方案如何建立一个自己的网站啊
  • 北京大兴黄村网站建设优化设计四年级上册语文答案
  • 飘仙我的网站加上www不能访问西安竞价推广托管
  • 做测试题的网站谷歌广告上海有限公司官网
  • 莱州市做网站的公司宁波seo推广
  • 贵州华瑞网站建设有限公司社交媒体营销三种方式
  • 做艺术品展览的网站58同城推广
  • 昆明网站建设公司小程序百度推广代理商加盟
  • 网站开发前景咋样突发大事震惊全国
  • 做导航网站成本1000个关键词
  • 容桂销售型网站建设营销型网站建设排名
  • 园区网络建设方案做seo推广公司
  • 有风格的网站中国世界排名
  • 网站主办者冲突六安seo
  • 做图赚钱的网站有哪些新媒体运营培训学校
  • 做外围什么网站有客户网络营销推广方案3篇
  • 培睿网站开发与设计桂林网页
  • 阿里巴巴网站备案号百度推广客户端下载安装
  • 东营网站排名软文案例大全300字
  • 做网站设计怎么进企业百度推广费用多少钱
  • php做动漫网站百度问答库
  • 推广型网站如何建站seo自学网
  • 杭州外贸网站建设公司价格seo推广骗局
  • 个人博客网站开发的原因完整的社群营销方案
  • 江门模板建站定制网店运营工作内容
  • 西安营销型网站制作制作网站教程