网络编程定时器一:使用升序链表

linux网络编程二十一:利用SIGALRM信号,实现一个简单的基于升序链表的定时器 由alarm和setitimer函数设置的实时闹钟一旦超时 阅读详情

之前一直对定时器这块不熟,今天来练练手。首先我们来看实现定时器的第一种方式,升序链表。

网络编程中应用层的定时器是很有必要的,这可以让服务端主动关闭时间很久的非活跃连接。另外一种解决方案是TCP的keepalive,但它只能检测真正的死连接,即客端主机断电,或者网线被拔掉这种情况。如果客端连接上,但什么都不做,keepalive是毫无办法的,它只能一定时间后不断的向客户端发送心跳包。

定时器通常至少要包含两个成员:一个超时时间(相对时间或绝对时间)和一个任务毁掉函数。有的时候还可能包含回调函数被执行时需要传入的参数,以及是否重启定时器等信息。如果使用双向链表,自然还需要指针成员。

我们将是用time函数作为定时器时间函数,它是相对时间,即从1970年某天到现在的描述,是一个数值,很容易用它和当前时间比较,后文分析。

下面实现了一个简单的升序定时器链表。升序定时器链表将其中定时器按照超时时间做升序排序。

#ifndef LIST_TIMER_H
#define LIST_TIMER_H

#include <time.h>
#include <memory>
#include <netinet/in.h>
#include <assert.h>

static const int BUFFER_SIZE = 64; 

class util_timer;   //前向声明

class client_data {
public:
    sockaddr_in                 addr_;    //客户端地址
    int                         sockfd_;  //客户端connfd
    char                        buf_[BUFFER_SIZE];  //每个客户端的缓冲区
    std::shared_ptr<util_timer> timer_;   //每个客户端的定时器
};

class util_timer {
public: //default constructor
    void (*timeout_callback_)(client_data* user_data);   //超时回调函数
public:
    time_t                       expire_;     //任务的超时时间,这里使用绝对时间
    client_data*                 user_data_;     //FIXME: how to replace it as a smart pointer.   //回调函数处理的客户数据,由电石气的执行者传给回调函数
    std::shared_ptr<util_timer>  prev_;   //指向前一个定时器
    std::shared_ptr<util_timer>  next_;   //指向下一个定时器
};

//定时器链表,它是一个升序、双向链表
class sort_timer_list { 
public: //default constructor and destructor
    void add_timer(const std::shared_ptr<util_timer>& timer);
    void adjust_timer(const std::shared_ptr<util_timer>& timer);
    void del_timer(const std::shared_ptr<util_timer>& timer);
    void tick();
private:
    void add_timer(const std::shared_ptr<util_timer>& timer,
                   const std::shared_ptr<util_timer>& lst_head);
private:
    std::shared_ptr<util_timer> head_;
    std::shared_ptr<util_timer> tail_;
};

//将目标定时器timer添加到链表中
void sort_timer_list::add_timer(const std::shared_ptr<util_timer>& timer)
{
    assert(timer != NULL);

    if(head_ == NULL){
        head_ = tail_ = timer;
        return;
    }
    //如果目标定时器的超时时间小于当前链表中所有定时器的超时时间,则把该定时器插入链表头部,作为链表的头节点。否则就需要调用重载函数add_timer把它插入到链表中合适的位置,以保证链表的升序特性
    if(timer->expire_ < head_->expire_){
        timer->next_ = head_;
        head_->prev_ = timer;
        head_ = timer;
    }
    else
        add_timer(timer, head_);  //invoke priva
flink定位反压节点 在 Apache Flink 中定位反压(Backpressure)节点需要结合监控工具和作业行为分析。 阅读详情

相关推荐

在 CentOS Stream 10 上搭建 Kubernetes 集群并支持开发调试与日志查看

搭建 Kubernetes 集群的每个步骤详细的文档。

灵犀物润 1660

AOSP Android14 Launcher3——动画核心类QuickstepTransitionManager详解

是一个复杂但核心的动画管理器。它利用 Android 的远程动画机制,拦截系统默认的窗口切换,并替换为高度定制、与 Launcher UI 深度集成的平滑过渡动画。当用户从一个应用程序通过手势或按键返回到 Launcher (桌面) 时,它负责创建和运行动画,使得应用程序窗口能够平滑地过渡(通常是缩小)到 Launcher 上的对应目标(图标、小部件或屏幕中心),同时 Launcher 界面元素(工作区、背景等)恢复显示。计算动画所需的各种参数,如窗口的起始/结束位置、缩放比例、透明度、圆角、裁剪区域等。

Micheal_Yang's Blog 2697

卫星载荷应用方案

本文将从技术和应用层面探讨卫星载荷的应用方案,分析各个领域的特点和挑战,以期为卫星载荷的应用提供一定的指导和参考。卫星载荷应用方案涵盖了通信、地球观测、气象预报、导航定位等诸多领域在每一个领域中,都存在着不同的技术挑战和应用需求。随着技术的进步和需求的变化,卫星载荷应用方案将不断发展和完善,为人类社会的进步和发展做出更大的贡献。用户可以通过接收多颗卫星的信号,计算自身的位置和速度信息。在覆盖扩展方面,可以采用多星座、MEO、GEO 等不同轨道高度的卫星布局,结合卫星的特点和应用需求,实现覆盖范围的扩展。

muyangjun的专栏 914

从零开始学版图(二)-----------差分放大电路

从零开始学版图

m0_56112720的博客 8590

基于stm32只能台灯控制系统设计

摘要:随着电子技术逐渐的发展进步,智能化设备已经开始普及到人们的生活之中。通过电子芯片实现了智能化的服务,将科技与生活紧密的连接,实现了科技改变生活的目的。本次通过单片机实现多功能台灯设计。整体设备通过单片机实现外部的信号与数据的检测,通过单片机实现了控制输出。围绕STM32单片机的最小系统搭建外围电路设计,多功能护眼台灯系统的外围电路主要包括了输入采集传感器与输出控制电路,采用按键作为参数的设置,采用ADC0832作为AD采集芯片采集模拟量信号。通过光线检测模块实现对光线的采集,采用超声波模块实现输入信息

m0_74026776的博客 788

共享单车数据抓取与分析:使用Python爬虫抓取共享单车使用数据与地图信息

通过本篇博客,我们展示了如何使用Python爬虫抓取共享单车的使用数据和地图信息,并通过简单的数据分析得出有价值的见解。在实际应用中,数据的收集与分析不仅能帮助城市管理者更好地规划单车站点,还能为用户提供更精准的单车使用体验。未来,我们可以将此分析与机器学习模型相结合,进一步预测单车的使用趋势,优化调度算法,实现更加智能的共享单车管理。

2201_76125261的博客 2215

从零开始理解Linux中断架构(1)-前言

前段时间在转行手撸WIFI路由器,搞wifi路由器需要理解网络驱动程序,以太网卡驱动程序,无线WIFI驱动程序,而网卡驱动的关键路径就在中断程序中,需要了解NIC设备驱动程序如何收发数据,为了彻底的知道数据包是如何二层传递上来的,又需要了解一点Linux中断系统。第一次看到这张表是无感的,大概能够看懂的就是那个中断次数,因为不停的cat,这个数值会一直不停的增加。第一列是逻辑中断号,第二三列是中断次数,第四列是中断控制器的名字,第五列是硬件中断号,第六列 中断类型,第七列是 中断源关联设备。

maxleng的专栏 886

自监督学习原理与代码实战案例讲解

自监督学习原理与代码实战案例讲解 作者:禅与计算机程序设计艺术 1. 背景介绍 1.1 自监督学习的起源与发展 1.1.1 监督学习的局限性

AI天才研究院 633

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

迈瑞BS系列全自动生化分析仪LIS协议接口手册(内含HL7和ASTM)

迈瑞BS系列全自动生化分析仪LIS协议接口手册,内含HL7和ASTM)

假人有限元模型

假人模型,车辆碰撞假人有限元模型,适合做乘员安全的研究者利用

Statistics and Machine Learning Toolbox

Statistics and Machine Learning Toolbox(带书签),MATLAB统计学习工具

上一篇: 257. Binary Tree Paths(打印二叉树所有路径)
下一篇: 123. Best Time to Buy and Sell Stock III(同小米风口的猪)
FreeeLinux
博客等级 码龄11年 421粉丝 356原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值
⌂ 换网址