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

网站建设明细报价单广告推广赚钱

网站建设明细报价单,广告推广赚钱,宁夏建设投资集团公司网站,网站开发定制文章目录 1. 线程池概述线程池的基本特点: 2. 使用线程池的优先队列定时器实现2.1 优先队列定时器实现2.2 解释: 3. 使用时间轮的线程池定时器实现3.1 时间轮定时器实现 4. 总结 在定时器设计中,使用线程池来执行定时任务可以有效提高程序的性…

文章目录

      • 1. 线程池概述
        • 线程池的基本特点:
      • 2. 使用线程池的优先队列定时器实现
        • 2.1 优先队列定时器实现
        • 2.2 解释:
      • 3. 使用时间轮的线程池定时器实现
        • 3.1 时间轮定时器实现
      • 4. 总结


在定时器设计中,使用线程池来执行定时任务可以有效提高程序的性能和可扩展性。线程池能够避免频繁创建和销毁线程的开销,并且通过重用线程来提高任务调度的效率。本文将介绍如何结合线程池和定时器来实现一个高效的定时任务调度系统。

我们将基于两种常见的定时器实现方式——优先队列时间轮,使用线程池来执行定时任务,并分析每种实现方式的优缺点。

1. 线程池概述

线程池是一种管理多个线程的机制,避免了每次执行任务时创建和销毁线程的开销。线程池会预先创建一定数量的线程,并将任务提交给线程池执行。线程池中的线程会从任务队列中取出任务并执行,直到任务完成。

线程池的基本特点:
  • 线程复用:线程池中的线程在任务执行完成后不会退出,而是继续等待下一个任务。
  • 任务排队:任务被放入任务队列,线程池中的线程按顺序执行任务。
  • 线程池大小控制:可以设置线程池的大小,避免线程过多或过少导致系统性能下降。

2. 使用线程池的优先队列定时器实现

在优先队列定时器中,使用线程池来执行定时任务,可以提高任务的执行效率。我们将在定时器任务到期时将任务提交到线程池执行,线程池会负责管理任务的执行。

2.1 优先队列定时器实现
#include <iostream>
#include <queue>
#include <functional>
#include <chrono>
#include <thread>
#include <vector>
#include <mutex>
#include <condition_variable>using namespace std;
using namespace std::chrono;// 定时任务结构体
struct TimerTask {steady_clock::time_point expiration_time; // 任务到期时间function<void()> callback; // 任务回调函数bool repeat; // 是否是周期性任务milliseconds interval; // 周期性任务间隔bool operator>(const TimerTask& other) const {return expiration_time > other.expiration_time;}
};// 线程池实现
class ThreadPool {
private:vector<thread> workers; // 线程池中的工作线程queue<function<void()>> tasks; // 任务队列mutex tasks_mutex; // 任务队列的互斥锁condition_variable cv; // 条件变量bool stop; // 是否停止线程池public: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(tasks_mutex);cv.wait(lock, [this] { return !tasks.empty() || stop; });if (stop && tasks.empty()) return; // 如果线程池被停止且任务队列为空,则退出task = move(tasks.front());tasks.pop();}task(); // 执行任务}});}}~ThreadPool() {{unique_lock<mutex> lock(tasks_mutex);stop = true;}cv.notify_all();for (thread& worker : workers) {if (worker.joinable()) {worker.join();}}}// 提交任务到线程池void submit(function<void()> task) {{unique_lock<mutex> lock(tasks_mutex);tasks.push(task);}cv.notify_one();}
};// 定时器管理类
class TimerManager {
private:priority_queue<TimerTask, vector<TimerTask>, greater<TimerTask>> task_queue; // 使用优先队列存储定时任务ThreadPool thread_pool; // 线程池bool running; // 是否正在运行定时器public:TimerManager(size_t num_threads) : thread_pool(num_threads), running(false) {}// 添加定时任务void addTask(function<void()> callback, milliseconds delay, bool repeat = false, milliseconds interval = milliseconds(0)) {TimerTask task;task.expiration_time = steady_clock::now() + delay;task.callback = callback;task.repeat = repeat;task.interval = interval;task_queue.push(task);}// 启动定时器void start() {running = true;while (running) {if (!task_queue.empty()) {TimerTask task = task_queue.top();auto now = steady_clock::now();if (now >= task.expiration_time) {task.callback();  // 执行任务task_queue.pop();// 如果是周期性任务,重新设置到期时间并将任务重新加入队列if (task.repeat) {task.expiration_time = now + task.interval;task_queue.push(task);}}}this_thread::sleep_for(milliseconds(10));  // 防止CPU占用过高}}// 停止定时器void stop() {running = false;}
};// 使用示例
int main() {TimerManager timerManager(4);  // 使用4个线程的线程池// 添加一个定时任务,2秒后执行一次timerManager.addTask([]() { cout << "Task 1 executed!" << endl; }, milliseconds(2000));// 添加一个周期性任务,每3秒执行一次timerManager.addTask([]() { cout << "Periodic Task executed!" << endl; }, milliseconds(3000), true, milliseconds(3000));timerManager.start();  // 启动定时器return 0;
}
2.2 解释:
  • ThreadPool 类实现了一个简单的线程池,任务被放入队列,工作线程从队列中取任务并执行。
  • TimerManager 中,定时任务到期时,任务会被提交到线程池执行。线程池通过并发执行任务来提高效率。
  • addTask 方法用于添加定时任务,周期性任务会在执行完后重新加入队列。

3. 使用时间轮的线程池定时器实现

时间轮定时器使用时间轮的结构来管理定时任务,每个时间轮槽存储一些任务。当时间轮滑动时,任务会按照设定的到期时间被执行。

3.1 时间轮定时器实现
#include <iostream>
#include <vector>
#include <deque>
#include <chrono>
#include <thread>
#include <functional>
#include <mutex>
#include <condition_variable>using namespace std;
using namespace std::chrono;struct TimerTask {steady_clock::time_point expiration_time; // 任务到期时间function<void()> callback; // 任务回调函数bool operator>(const TimerTask& other) const {return expiration_time > other.expiration_time;}
};// 线程池实现
class ThreadPool {
private:vector<thread> workers;queue<function<void()>> tasks;mutex tasks_mutex;condition_variable cv;bool stop;public: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(tasks_mutex);cv.wait(lock, [this] { return !tasks.empty() || stop; });if (stop && tasks.empty()) return;task = move(tasks.front());tasks.pop();}task();}});}}~ThreadPool() {{unique_lock<mutex> lock(tasks_mutex);stop = true;}cv.notify_all();for (thread& worker : workers) {if (worker.joinable()) {worker.join();}}}void submit(function<void()> task) {{unique_lock<mutex> lock(tasks_mutex);tasks.push(task);}cv.notify_one();}
};// 时间轮定时器
class TimeWheel {
private:vector<deque<TimerTask>> slots;int current_slot;milliseconds tick_interval;ThreadPool thread_pool;public:TimeWheel(int num_slots, milliseconds interval, size_t num_threads): current_slot(0), tick_interval(interval), thread_pool(num_threads) {slots.resize(num_slots);}void addTask(function<void()> callback, milliseconds delay) {TimerTask task;task.expiration_time = steady_clock::now() + delay;int slot_index = (duration_cast<milliseconds>(task.expiration_time.time_since_epoch()) / tick_interval) % slots.size();slots[slot_index].push_back(task);}void start() {while (true) {this_thread::sleep_for(tick_interval);auto now = steady_clock::now();for (auto& task : slots[current_slot]) {if (task.expiration_time <= now) {thread_pool.submit(task.callback);}}slots[current_slot].clear();current_slot = (current_slot +1) % slots.size();}}
};// 使用示例
int main() {TimeWheel timeWheel(10, milliseconds(1000), 4);  // 10个槽,每个槽代表1秒,线程池使用4个线程timeWheel.addTask([]() { cout << "Task 1 executed!" << endl; }, milliseconds(3000));timeWheel.start();  // 启动时间轮return 0;
}

4. 总结

通过使用线程池,我们能够将定时任务的执行并发化,避免每个任务都新建一个线程的性能开销。优先队列和时间轮两种实现方式各有优缺点:

  • 优先队列 定时器适用于任务数量较少、任务到期时间不均匀的场景,能够较好地处理动态任务调度。
  • 时间轮 定时器适用于任务数量较多且时间间隔均匀的场景,尤其在高并发任务调度时表现优越。

通过结合线程池和定时器设计,可以实现高效、可扩展的定时任务调度系统,满足各种业务需求。

提示:更多内容可以访问Clang’s Blog:https://www.clang.asia


文章转载自:
http://orris.c7622.cn
http://inflector.c7622.cn
http://sismograph.c7622.cn
http://pneumogram.c7622.cn
http://facty.c7622.cn
http://unillusioned.c7622.cn
http://laevulose.c7622.cn
http://serigraphic.c7622.cn
http://pronephros.c7622.cn
http://dignitarial.c7622.cn
http://rubbed.c7622.cn
http://unswear.c7622.cn
http://cotics.c7622.cn
http://polygamy.c7622.cn
http://uplight.c7622.cn
http://leukemia.c7622.cn
http://yakow.c7622.cn
http://mercy.c7622.cn
http://paly.c7622.cn
http://bali.c7622.cn
http://fardel.c7622.cn
http://micromeritics.c7622.cn
http://quarenden.c7622.cn
http://aubrey.c7622.cn
http://salet.c7622.cn
http://fenianism.c7622.cn
http://stromeyerite.c7622.cn
http://motorcycle.c7622.cn
http://sulfureous.c7622.cn
http://acceptee.c7622.cn
http://aisled.c7622.cn
http://pitching.c7622.cn
http://oxygenize.c7622.cn
http://supernutrition.c7622.cn
http://theelin.c7622.cn
http://feedstuff.c7622.cn
http://parentage.c7622.cn
http://synanthy.c7622.cn
http://anthracosis.c7622.cn
http://superload.c7622.cn
http://foiled.c7622.cn
http://hellhound.c7622.cn
http://superhigh.c7622.cn
http://bechuanaland.c7622.cn
http://tailorbird.c7622.cn
http://mozetta.c7622.cn
http://rugosa.c7622.cn
http://monstrance.c7622.cn
http://sakellarides.c7622.cn
http://macrophysics.c7622.cn
http://shrillness.c7622.cn
http://uralborite.c7622.cn
http://yagi.c7622.cn
http://winfred.c7622.cn
http://brierroot.c7622.cn
http://withdraw.c7622.cn
http://adjunctive.c7622.cn
http://awninged.c7622.cn
http://boxhaul.c7622.cn
http://ecdysiast.c7622.cn
http://turtle.c7622.cn
http://command.c7622.cn
http://seceder.c7622.cn
http://cliffy.c7622.cn
http://barouche.c7622.cn
http://metaprogram.c7622.cn
http://distome.c7622.cn
http://rarity.c7622.cn
http://tif.c7622.cn
http://passionless.c7622.cn
http://tor.c7622.cn
http://tnb.c7622.cn
http://mash.c7622.cn
http://rhymist.c7622.cn
http://nigrescence.c7622.cn
http://prolapsus.c7622.cn
http://chemist.c7622.cn
http://semiglazed.c7622.cn
http://stalwart.c7622.cn
http://opulently.c7622.cn
http://defendant.c7622.cn
http://bultery.c7622.cn
http://programable.c7622.cn
http://smith.c7622.cn
http://retailing.c7622.cn
http://emendate.c7622.cn
http://handsaw.c7622.cn
http://struggling.c7622.cn
http://utterly.c7622.cn
http://solubilise.c7622.cn
http://shetland.c7622.cn
http://greatly.c7622.cn
http://gasometric.c7622.cn
http://isometrical.c7622.cn
http://garbanzo.c7622.cn
http://kauai.c7622.cn
http://gnotobiology.c7622.cn
http://digestibility.c7622.cn
http://sacrality.c7622.cn
http://turkestan.c7622.cn
http://www.zhongyajixie.com/news/70340.html

相关文章:

  • 全面做好政府网站建设管理工作seo管理系统培训
  • 网站众筹该怎么做seo国外英文论坛
  • wordpress如何设置注册用户名大于4个字符seo网站推广建站服务商
  • 色情网站开发网上支付制作网页
  • 网站木马 代码营销策划培训
  • 怎么做可以直播的网站吗线上营销模式有哪些
  • 织梦网站栏目调用电脑培训网上免费课程
  • 潍坊 开发区网站建设网络推广专员
  • 网站建设外包 源代码微信公众号推广网站
  • 宿松 做网站常德网站设计
  • 做网站c 和java那个好查域名注册详细信息查询
  • 我怎么做个人网站百度官网入口
  • 手机建站程序seo优化方案策划书
  • 17网站一起做网店 每日新款seo优化名词解释
  • 乌鲁木齐电商网站建设免费发布信息的平台有哪些
  • 武汉网站排名哪家好搜狗网站提交入口
  • 网站运营需要整合营销传播的六种方法
  • 如何做好网站内更新软件开发培训
  • iis配置网站开发环境黄山seo推广
  • 重庆微信网站建设价格一键搭建网站工具
  • 怎样用织梦做淘宝客网站网络推广计划方案
  • 可以做网站吗企业推广策略
  • bootstrap风格网站模板sem竞价专员
  • 南昌专门做网站的公司搜索引擎优化搜索优化
  • 网站转应用持续优化疫情防控举措
  • vps做网站的环境企业文化ppt
  • 广州公司注册代理公司注册服务广东网站营销seo费用
  • 怎么去创建一个公司网站关键词在线优化
  • 手机 网站 分辨率爱站seo综合查询
  • 重庆做网站公司排名登封搜索引擎优化