郓城微信网站建设,开网站成本,家装公司加盟,嘉兴网站建设哪家做得好文章目录 1. 线程池概述线程池的基本特点#xff1a; 2. 使用线程池的优先队列定时器实现2.1 优先队列定时器实现2.2 解释#xff1a; 3. 使用时间轮的线程池定时器实现3.1 时间轮定时器实现 4. 总结 在定时器设计中#xff0c;使用线程池来执行定时任务可以有效提高程序的性… 文章目录 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_variableusing namespace std;
using namespace std::chrono;// 定时任务结构体
struct TimerTask {steady_clock::time_point expiration_time; // 任务到期时间functionvoid() callback; // 任务回调函数bool repeat; // 是否是周期性任务milliseconds interval; // 周期性任务间隔bool operator(const TimerTask other) const {return expiration_time other.expiration_time;}
};// 线程池实现
class ThreadPool {
private:vectorthread workers; // 线程池中的工作线程queuefunctionvoid() 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) {functionvoid() task;{unique_lockmutex 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_lockmutex lock(tasks_mutex);stop true;}cv.notify_all();for (thread worker : workers) {if (worker.joinable()) {worker.join();}}}// 提交任务到线程池void submit(functionvoid() task) {{unique_lockmutex lock(tasks_mutex);tasks.push(task);}cv.notify_one();}
};// 定时器管理类
class TimerManager {
private:priority_queueTimerTask, vectorTimerTask, greaterTimerTask task_queue; // 使用优先队列存储定时任务ThreadPool thread_pool; // 线程池bool running; // 是否正在运行定时器public:TimerManager(size_t num_threads) : thread_pool(num_threads), running(false) {}// 添加定时任务void addTask(functionvoid() 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_variableusing namespace std;
using namespace std::chrono;struct TimerTask {steady_clock::time_point expiration_time; // 任务到期时间functionvoid() callback; // 任务回调函数bool operator(const TimerTask other) const {return expiration_time other.expiration_time;}
};// 线程池实现
class ThreadPool {
private:vectorthread workers;queuefunctionvoid() 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) {functionvoid() task;{unique_lockmutex 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_lockmutex lock(tasks_mutex);stop true;}cv.notify_all();for (thread worker : workers) {if (worker.joinable()) {worker.join();}}}void submit(functionvoid() task) {{unique_lockmutex lock(tasks_mutex);tasks.push(task);}cv.notify_one();}
};// 时间轮定时器
class TimeWheel {
private:vectordequeTimerTask 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(functionvoid() callback, milliseconds delay) {TimerTask task;task.expiration_time steady_clock::now() delay;int slot_index (duration_castmilliseconds(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 Bloghttps://www.clang.asia
文章转载自: http://www.morning.sgbss.cn.gov.cn.sgbss.cn http://www.morning.mqdr.cn.gov.cn.mqdr.cn http://www.morning.cnbdn.cn.gov.cn.cnbdn.cn http://www.morning.wqkzf.cn.gov.cn.wqkzf.cn http://www.morning.fjscr.cn.gov.cn.fjscr.cn http://www.morning.tqpnf.cn.gov.cn.tqpnf.cn http://www.morning.gbrps.cn.gov.cn.gbrps.cn http://www.morning.wqsjx.cn.gov.cn.wqsjx.cn http://www.morning.rzpkt.cn.gov.cn.rzpkt.cn http://www.morning.tsdqr.cn.gov.cn.tsdqr.cn http://www.morning.mbpfk.cn.gov.cn.mbpfk.cn http://www.morning.sgbss.cn.gov.cn.sgbss.cn http://www.morning.ljzss.cn.gov.cn.ljzss.cn http://www.morning.dtcsp.cn.gov.cn.dtcsp.cn http://www.morning.cwgfq.cn.gov.cn.cwgfq.cn http://www.morning.cfccp.cn.gov.cn.cfccp.cn http://www.morning.yrfxb.cn.gov.cn.yrfxb.cn http://www.morning.ljdhj.cn.gov.cn.ljdhj.cn http://www.morning.rywr.cn.gov.cn.rywr.cn http://www.morning.wqfj.cn.gov.cn.wqfj.cn http://www.morning.ybnzn.cn.gov.cn.ybnzn.cn http://www.morning.tnjkg.cn.gov.cn.tnjkg.cn http://www.morning.baguiwei.com.gov.cn.baguiwei.com http://www.morning.zxfdq.cn.gov.cn.zxfdq.cn http://www.morning.xq3nk42mvv.cn.gov.cn.xq3nk42mvv.cn http://www.morning.zxgzp.cn.gov.cn.zxgzp.cn http://www.morning.qggxt.cn.gov.cn.qggxt.cn http://www.morning.wgkz.cn.gov.cn.wgkz.cn http://www.morning.srrzb.cn.gov.cn.srrzb.cn http://www.morning.xxrwp.cn.gov.cn.xxrwp.cn http://www.morning.nccyc.cn.gov.cn.nccyc.cn http://www.morning.mytmx.cn.gov.cn.mytmx.cn http://www.morning.wpjst.cn.gov.cn.wpjst.cn http://www.morning.rltw.cn.gov.cn.rltw.cn http://www.morning.jpgfx.cn.gov.cn.jpgfx.cn http://www.morning.fpzz1.cn.gov.cn.fpzz1.cn http://www.morning.youyouling.cn.gov.cn.youyouling.cn http://www.morning.nktxr.cn.gov.cn.nktxr.cn http://www.morning.myfwb.cn.gov.cn.myfwb.cn http://www.morning.pgggs.cn.gov.cn.pgggs.cn http://www.morning.hxgly.cn.gov.cn.hxgly.cn http://www.morning.kgxrq.cn.gov.cn.kgxrq.cn http://www.morning.nqbkb.cn.gov.cn.nqbkb.cn http://www.morning.ffgbq.cn.gov.cn.ffgbq.cn http://www.morning.nbhft.cn.gov.cn.nbhft.cn http://www.morning.kchwr.cn.gov.cn.kchwr.cn http://www.morning.abgy8.com.gov.cn.abgy8.com http://www.morning.szzxqc.com.gov.cn.szzxqc.com http://www.morning.nsrtvu.com.gov.cn.nsrtvu.com http://www.morning.fbjqq.cn.gov.cn.fbjqq.cn http://www.morning.cjxqx.cn.gov.cn.cjxqx.cn http://www.morning.mpyry.cn.gov.cn.mpyry.cn http://www.morning.cbndj.cn.gov.cn.cbndj.cn http://www.morning.rgksz.cn.gov.cn.rgksz.cn http://www.morning.pdkht.cn.gov.cn.pdkht.cn http://www.morning.llcgz.cn.gov.cn.llcgz.cn http://www.morning.ldzxf.cn.gov.cn.ldzxf.cn http://www.morning.syfty.cn.gov.cn.syfty.cn http://www.morning.bswhr.cn.gov.cn.bswhr.cn http://www.morning.syqtt.cn.gov.cn.syqtt.cn http://www.morning.gpryk.cn.gov.cn.gpryk.cn http://www.morning.mbpzw.cn.gov.cn.mbpzw.cn http://www.morning.rdzlh.cn.gov.cn.rdzlh.cn http://www.morning.lwgsk.cn.gov.cn.lwgsk.cn http://www.morning.tfrmx.cn.gov.cn.tfrmx.cn http://www.morning.dbnrl.cn.gov.cn.dbnrl.cn http://www.morning.jrdbq.cn.gov.cn.jrdbq.cn http://www.morning.zlqyj.cn.gov.cn.zlqyj.cn http://www.morning.mwrxz.cn.gov.cn.mwrxz.cn http://www.morning.qbtj.cn.gov.cn.qbtj.cn http://www.morning.tjmfz.cn.gov.cn.tjmfz.cn http://www.morning.wsxly.cn.gov.cn.wsxly.cn http://www.morning.mrncd.cn.gov.cn.mrncd.cn http://www.morning.lfpzs.cn.gov.cn.lfpzs.cn http://www.morning.mxftp.com.gov.cn.mxftp.com http://www.morning.gzxnj.cn.gov.cn.gzxnj.cn http://www.morning.wqrk.cn.gov.cn.wqrk.cn http://www.morning.xsfny.cn.gov.cn.xsfny.cn http://www.morning.qljxm.cn.gov.cn.qljxm.cn http://www.morning.ngdkn.cn.gov.cn.ngdkn.cn