0
  • 聊天消息
  • 系统消息
  • 评论与回复
登录后你可以
  • 下载海量资料
  • 学习在线课程
  • 观看技术视频
  • 写文章/发帖/加入社区
创作中心

完善资料让更多小伙伴认识你,还能领取20积分哦,立即完善>

3天内不再提示

多级时间轮实现框架

科技绿洲 来源:Linux开发架构之路 作者:Linux开发架构之路 2023-11-11 15:49 次阅读

一. 多级时间轮实现框架

图片

上图是5个时间轮级联的效果图。中间的大轮是工作轮,只有在它上的任务才会被执行;其他轮上的任务时间到后迁移到下一级轮上,他们最终都会迁移到工作轮上而被调度执行。

多级时间轮的原理也容易理解:就拿时钟做说明,秒针转动一圈分针转动一格;分针转动一圈时针转动一格;同理时间轮也是如此:当低级轮转动一圈时,高一级轮转动一格,同时会将高一级轮上的任务重新分配到低级轮上。从而实现了多级轮级联的效果。

1.1 多级时间轮对象

图片

多级时间轮应该至少包括以下内容:

  • 每一级时间轮对象
  • 轮子上指针的位置

关于轮子上指针的位置有一个比较巧妙的办法:那就是位运算。比如定义一个无符号整型的数:

图片

通过获取当前的系统时间便可以通过位操作转换为时间轮上的时间,通过与实际时间轮上的时间作比较,从而确定时间轮要前进调度的时间,进而操作对应时间轮槽位对应的任务。

为什么至少需要这两个成员呢?

  • 定义多级时间轮,首先需要明确的便是级联的层数,也就是说需要确定有几个时间轮。
  • 轮子上指针位置,就是当前时间轮运行到的位置,它与真实时间的差便是后续时间轮需要调度执行,它们的差值是时间轮运作起来的驱动力。

多级时间轮对象的定义

//实现5级时间轮 范围为0~ (2^8 * 2^6 * 2^6 * 2^6 *2^6)=2^32
struct tvec_base
{
    unsigned long 		current_index;   
    pthread_t  			thincrejiffies;
    pthread_t  			threadID;
    struct tvec_root 	tv1;	/*第一个轮*/
    struct tvec      	tv2;	/*第二个轮*/
    struct tvec      	tv3;	/*第三个轮*/
    struct tvec      	tv4;	/*第四个轮*/
    struct tvec      	tv5;	/*第五个轮*/
};

1.2 时间轮对象

图片

我们知道每一个轮子实际上都是一个哈希表,上面我们只是实例化了五个轮子的对象,但是五个轮子具体包含什么,有几个槽位等等没有明确(即struct tvec和struct tvec_root)。

#define TVN_BITS 		6
#define TVR_BITS 		8
#define TVN_SIZE 		(1< 

此外,每一个时间轮都是哈希表,因此它的类型应该至少包含两个指针域来实现双向链表的功能。这里我们为了方便使用通用的struct list_head的双向链表结构。

1.3 定时任务对象

图片

定时器的主要工作是为了在未来的特定时间完成某项任务,而这个任务经常包含以下内容:

  • 任务的处理逻辑(回调函数)
  • 任务的参数
  • 双向链表节点
  • 到时时间

定时任务对象的定义

typedef void (*timeouthandle)(unsigned long );

struct timer_list{
    struct list_head entry;          //将时间连接成链表
    unsigned long expires;           //超时时间
    void (*function)(unsigned long); //超时后的处理函数
    unsigned long data;              //处理函数的参数
    struct tvec_base *base;          //指向时间轮
};

在时间轮上的效果图:

图片

1.4 双向链表

在时间轮上我们采用双向链表的数据类型。采用双向链表的除了操作上比单链表复杂,多占一个指针域外没有其他不可接收的问题。而多占一个指针域在今天大内存的时代明显不是什么问题。至于双向链表操作的复杂性,我们可以通过使用通用的struct list结构来解决,因为双向链表有众多的标准操作函数,我们可以通过直接引用list.h头文件来使用他们提供的接口

struct list可以说是一个万能的双向链表操作框架,我们只需要在自定义的结构中定义一个struct list对象即可使用它的标准操作接口。同时它还提供了一个类似container_of的接口,在应用层一般叫做list_entry,因此我们可以很方便的通过struct list成员找到自定义的结构体的起始地址。

关于应用层的log.h, 我将在下面的代码中附上该文件。如果需要内核层的实现,可以直接从linux源码中获取。

1.5 联结方式

多级时间轮效果图:

图片

二. 多级时间轮C语言实现

2.1 双向链表头文件: list.h

提到双向链表,很多的源码工程中都会实现一系列的统一的双向链表操作函数。它们为双向链表封装了统计的接口,使用者只需要在自定义的结构中添加一个struct list_head结构,然后调用它们提供的接口,便可以完成双向链表的所有操作。这些操作一般都在list.h的头文件中实现。Linux源码中也有实现(内核态的实现)。他们实现的方式基本完全一样,只是实现的接口数量和功能上稍有差别。可以说这个list.h文件是学习操作双向链表的不二选择,它几乎实现了所有的操作:增、删、改、查、遍历、替换、清空等等。这里我拼凑了一个源码中的log.h函数,终于凑够了多级时间轮中使用到的接口。

图片

#if !defined(_BLKID_LIST_H) && !defined(LIST_HEAD)
#define _BLKID_LIST_H
#ifdef __cplusplus 
extern "C" {
#endif
/*
 * Simple doubly linked list implementation.
 *
 * Some of the internal functions ("__xxx") are useful when
 * manipulating whole lists rather than single entries, as
 * sometimes we already know the next/prev entries and we can
 * generate better code by using them directly rather than
 * using the generic single-entry routines.
 */
struct list_head {
	struct list_head *next, *prev;
};
#define LIST_HEAD_INIT(name) { &(name), &(name) }
#define LIST_HEAD(name) 
	struct list_head name = LIST_HEAD_INIT(name)
#define INIT_LIST_HEAD(ptr) do { 
	(ptr)- >next = (ptr); (ptr)- >prev = (ptr); 
} while (0)
static inline void
__list_add(struct list_head *entry,
                struct list_head *prev, struct list_head *next)
{
    next- >prev = entry;
    entry- >next = next;
    entry- >prev = prev;
    prev- >next = entry;
}
/**
 * Insert a new element after the given list head. The new element does not
 * need to be initialised as empty list.
 * The list changes from:
 *      head → some element → ...
 * to
 *      head → new element → older element → ...
 *
 * Example:
 * struct foo *newfoo = malloc(...);
 * list_add(&newfoo- >entry, &bar- >list_of_foos);
 *
 * @param entry The new element to prepend to the list.
 * @param head The existing list.
 */
static inline void
list_add(struct list_head *entry, struct list_head *head)
{
    __list_add(entry, head, head- >next);
}
/**
 * Append a new element to the end of the list given with this list head.
 *
 * The list changes from:
 *      head → some element → ... → lastelement
 * to
 *      head → some element → ... → lastelement → new element
 *
 * Example:
 * struct foo *newfoo = malloc(...);
 * list_add_tail(&newfoo- >entry, &bar- >list_of_foos);
 *
 * @param entry The new element to prepend to the list.
 * @param head The existing list.
 */
static inline void
list_add_tail(struct list_head *entry, struct list_head *head)
{
    __list_add(entry, head- >prev, head);
}
static inline void
__list_del(struct list_head *prev, struct list_head *next)
{
    next- >prev = prev;
    prev- >next = next;
}
/**
 * Remove the element from the list it is in. Using this function will reset
 * the pointers to/from this element so it is removed from the list. It does
 * NOT free the element itself or manipulate it otherwise.
 *
 * Using list_del on a pure list head (like in the example at the top of
 * this file) will NOT remove the first element from
 * the list but rather reset the list as empty list.
 *
 * Example:
 * list_del(&foo- >entry);
 *
 * @param entry The element to remove.
 */
static inline void
list_del(struct list_head *entry)
{
    __list_del(entry- >prev, entry- >next);
}
static inline void
list_del_init(struct list_head *entry)
{
    __list_del(entry- >prev, entry- >next);
    INIT_LIST_HEAD(entry);
}
static inline void list_move_tail(struct list_head *list,
				  struct list_head *head)
{
	__list_del(list- >prev, list- >next);
	list_add_tail(list, head);
}
/**
 * Check if the list is empty.
 *
 * Example:
 * list_empty(&bar- >list_of_foos);
 *
 * @return True if the list contains one or more elements or False otherwise.
 */
static inline int
list_empty(struct list_head *head)
{
    return head- >next == head;
}
/**
 * list_replace - replace old entry by new one
 * @old : the element to be replaced
 * @new : the new element to insert
 *
 * If @old was empty, it will be overwritten.
 */
static inline void list_replace(struct list_head *old,
				struct list_head *new)
{
	new- >next = old- >next;
	new- >next- >prev = new;
	new- >prev = old- >prev;
	new- >prev- >next = new;
}
/**
 * Retrieve the first list entry for the given list pointer.
 *
 * Example:
 * struct foo *first;
 * first = list_first_entry(&bar- >list_of_foos, struct foo, list_of_foos);
 *
 * @param ptr The list head
 * @param type Data type of the list element to retrieve
 * @param member Member name of the struct list_head field in the list element.
 * @return A pointer to the first list element.
 */
#define list_first_entry(ptr, type, member) 
    list_entry((ptr)- >next, type, member)
static inline void list_replace_init(struct list_head *old,
					struct list_head *new)
{
	list_replace(old, new);
	INIT_LIST_HEAD(old);
}
/**
 * list_entry - get the struct for this entry
 * @ptr:	the &struct list_head pointer.
 * @type:	the type of the struct this is embedded in.
 * @member:	the name of the list_struct within the struct.
 */
#define list_entry(ptr, type, member) 
	((type *)((char *)(ptr)-(unsigned long)(&((type *)0)- >member)))
/**
 * list_for_each - iterate over elements in a list
 * @pos:	the &struct list_head to use as a loop counter.
 * @head:	the head for your list.
 */
#define list_for_each(pos, head) 
	for (pos = (head)- >next; pos != (head); pos = pos- >next)
/**
 * list_for_each_safe - iterate over elements in a list, but don't dereference
 *                      pos after the body is done (in case it is freed)
 * @pos:	the &struct list_head to use as a loop counter.
 * @pnext:	the &struct list_head to use as a pointer to the next item.
 * @head:	the head for your list (not included in iteration).
 */
#define list_for_each_safe(pos, pnext, head) 
	for (pos = (head)- >next, pnext = pos- >next; pos != (head); 
	     pos = pnext, pnext = pos- >next)
#ifdef __cplusplus
}
#endif
#endif /* _BLKID_LIST_H */

这里面一般会用到一个重要实现:container_of, 它的原理这里不叙述

2.2 调试信息头文件: log.h

这个头文件实际上不是必须的,我只是用它来添加调试信息(代码中的errlog(), log()都是log.h中的宏函数)。它的效果是给打印的信息加上颜色,效果如下:

图片

log.h的代码如下:

#ifndef _LOG_h_
#define _LOG_h_
#include < stdio.h >
#define COL(x)  "�33[;" #x "m"
#define RED     COL(31)
#define GREEN   COL(32)
#define YELLOW  COL(33)
#define BLUE    COL(34)
#define MAGENTA COL(35)
#define CYAN    COL(36)
#define WHITE   COL(0)
#define GRAY    "�33[0m"
#define errlog(fmt, arg...) do{     
    printf(RED"[#ERROR: Toeny Sun:"GRAY YELLOW" %s:%d]:"GRAY WHITE fmt GRAY, __func__, __LINE__, ##arg);
}while(0)
#define log(fmt, arg...) do{     
    printf(WHITE"[#DEBUG: Toeny Sun: "GRAY YELLOW"%s:%d]:"GRAY WHITE fmt GRAY, __func__, __LINE__, ##arg);
}while(0)
#endif

2.3 时间轮代码: timewheel.c

/*
 *毫秒定时器  采用多级时间轮方式  借鉴linux内核中的实现
 *支持的范围为1 ~  2^32 毫秒(大约有49天)
 *若设置的定时器超过最大值 则按最大值设置定时器
 **/
#include < stdio.h >
#include < stdlib.h >
#include < string.h >
#include < unistd.h >
#include < pthread.h >
#include < sys/time.h >
#include "list.h"
#include "log.h" 
#define TVN_BITS 		6
#define TVR_BITS 		8
#define TVN_SIZE 		(1< 

2.4 编译运行

toney@ubantu:/mnt/hgfs/em嵌入式学习记录/4. timerwheel/2. 多级时间轮$ ls
a.out  list.h  log.h  mutiTimeWheel.c
toney@ubantu:/mnt/hgfs/em嵌入式学习记录/4. timerwheel/2. 多级时间轮$ gcc mutiTimeWheel.c -lpthread
toney@ubantu:/mnt/hgfs/em嵌入式学习记录/4. timerwheel/2. 多级时间轮$ ./a.out 
[#DEBUG: Toeny Sun: mytimer:370]:100
[#DEBUG: Toeny Sun: mytimer:370]:100
[#DEBUG: Toeny Sun: mytimer:370]:100
[#DEBUG: Toeny Sun: mytimer:370]:100
[#DEBUG: Toeny Sun: mytimer:370]:100
[#DEBUG: Toeny Sun: mytimer:370]:100
[#DEBUG: Toeny Sun: mytimer:370]:100
[#DEBUG: Toeny Sun: mytimer:370]:100
[#DEBUG: Toeny Sun: mytimer:370]:100
[#DEBUG: Toeny Sun: mytimer:370]:100
[#DEBUG: Toeny Sun: mytimer:370]:100
[#DEBUG: Toeny Sun: mytimer:370]:100
[#DEBUG: Toeny Sun: mytimer:370]:100
[#DEBUG: Toeny Sun: mytimer:370]:100
[#DEBUG: Toeny Sun: mytimer:370]:100
[#DEBUG: Toeny Sun: mytimer:370]:100
[#DEBUG: Toeny Sun: mytimer:370]:100
[#DEBUG: Toeny Sun: mytimer:370]:100
[#DEBUG: Toeny Sun: mytimer:370]:100
[#DEBUG: Toeny Sun: mytimer:370]:100
[#DEBUG: Toeny Sun: mytimer:370]:100
[#DEBUG: Toeny Sun: mytimer:370]:100
[#DEBUG: Toeny Sun: mytimer:370]:100
[#DEBUG: Toeny Sun: mytimer:370]:100
[#DEBUG: Toeny Sun: mytimer:370]:100
[#DEBUG: Toeny Sun: mytimer:370]:100
[#DEBUG: Toeny Sun: mytimer:370]:100
[#DEBUG: Toeny Sun: mytimer:370]:100

从结果可以看出:如果添加的定时任务是比较耗时的操作,那么后续的任务也会被阻塞,可能一直到超时,甚至一直阻塞下去,这个取决于当前任务是否耗时。这个理论上是绝不能接受的:一个任务不应该也不能去影响其他的任务吧。但是目前没有对此问题进行改进和完善,以后有机会再继续完善吧。

声明:本文内容及配图由入驻作者撰写或者入驻合作网站授权转载。文章观点仅代表作者本人,不代表电子发烧友网立场。文章及其配图仅供工程师学习之用,如有内容侵权或者其他违规问题,请联系本站处理。 举报投诉
  • 参数
    +关注

    关注

    11

    文章

    1398

    浏览量

    31474
  • 函数
    +关注

    关注

    3

    文章

    3882

    浏览量

    61310
  • 代码
    +关注

    关注

    30

    文章

    4556

    浏览量

    66800
收藏 人收藏

    评论

    相关推荐

    使用cola_os软件定时器实现时间片轮询框架

    如果使用RTOS显得太浪费,这时候可以尝试使用使用cola_os这类基于软件定时器实现时间片轮询框架
    的头像 发表于 09-22 09:03 1107次阅读
    使用cola_os软件定时器<b class='flag-5'>实现时间</b>片轮询<b class='flag-5'>框架</b>

    多级时间轮定时器的原理及编程实现方案

    struct list可以说是一个万能的双向链表操作框架,我们只需要在自定义的结构中定义一个struct list对象即可使用它的标准操作接口。
    发表于 06-28 12:50 350次阅读
    <b class='flag-5'>多级</b><b class='flag-5'>时间</b>轮定时器的原理及编程<b class='flag-5'>实现</b>方案

    基于J2EE的数据通用性操作框架的研究与实现

    基于J2EE的数据通用性操作框架的研究与实现数据操作是基于J2EE的多级应用开发中常见而又具有通用性的重要一部分,而框架技术的研究可以实现
    发表于 06-17 09:35

    平衡小车设计

    系统基本框架实现对车身信息的采集。驱动直流电机,实现车体的平衡控制。二、项目设计   二平衡小车采用直流电机驱动方式,依靠陀螺仪和角加速度传感器采集平衡信息
    发表于 11-16 00:18

    制作库时如何分多级菜单

    使用 LabView有一段时间了,一直在想如何可以做好更好的使用及模块移植。最近一段时间做了不少的库、库进行多层继承敢制作过。但是发现有个问题就是库调用的属性只有一级菜单,不能进行分类。然而调用其内部的属性时却可以有多级,不知如
    发表于 01-20 16:31

    时间的种类有哪些?

    什么是单层时间?什么是多层时间
    发表于 11-06 06:15

    单片机c语言下如何实现lcd多级菜单?

    萌新求助,关于单片机c语言下lcd多级菜单的一种实现方法
    发表于 10-15 06:36

    如何去实现麦克纳姆的PID控制调试呢

    什么是麦克纳姆?麦克纳姆是怎样进行运动的?如何去实现麦克纳姆的PID控制调试呢?
    发表于 02-22 07:40

    基于RT-Thread+RA6M4的麦结构的底盘运动控制系统设计案例

    ,使其驱动4个麦的电机。其地盘可实现全向移动,即平面的纵向,横向移动和原地的旋转移动。应用背景在目前移动机器人开发中,除了仿生结构的机器人之外,麦结构的移动机器人和万向结构的移动
    发表于 08-17 14:50

    LCD多级菜单具体实现

    LCD多级菜单具体实现 //Last Modify Time:03/11/07 01:22 //ReadMe //屏宽:112 //屏高:64 #include reg51.h #include
    发表于 07-02 15:23 133次下载

    步进式加热炉多级网络监控系统的设计与实现_田海

    步进式加热炉多级网络监控系统的设计与实现_田海
    发表于 01-19 21:49 0次下载

    使用风扇实现多级通风

    电子发烧友网站提供《使用风扇实现多级通风.zip》资料免费下载
    发表于 11-23 10:21 0次下载
    使用风扇<b class='flag-5'>实现</b><b class='flag-5'>多级</b>通风

    Linux 编程之经典多级时间轮定时器(上)

    多级时间轮的原理也容易理解:就拿时钟做说明,秒针转动一圈分针转动一格;分针转动一圈时针转动一格;同理时间轮也是如此:当低级轮转动一圈时,高一级轮转动一格,同时会将高一级轮上的任务重新分配到低级轮上。从而
    的头像 发表于 04-21 14:45 463次阅读
    Linux 编程之经典<b class='flag-5'>多级</b><b class='flag-5'>时间</b>轮定时器(上)

    Linux 编程之经典多级时间轮定时器(下)

    多级时间轮的原理也容易理解:就拿时钟做说明,秒针转动一圈分针转动一格;分针转动一圈时针转动一格;同理时间轮也是如此:当低级轮转动一圈时,高一级轮转动一格,同时会将高一级轮上的任务重新分配到低级轮上。从而
    的头像 发表于 04-21 14:45 544次阅读

    多级时间实现框架

    一. 多级时间实现框架 上图是5个时间轮级联的效果图。中间的大轮是工作轮,只有在它上的任务才会被执行;其他轮上的任务
    的头像 发表于 06-22 14:57 519次阅读
    <b class='flag-5'>多级</b><b class='flag-5'>时间</b>轮<b class='flag-5'>实现</b><b class='flag-5'>框架</b>