基于setitimer实现允许单进程多次调用的定时器

原理

setitimer不能在进程中多次调用,考虑用链表管理调用。每个节点包含当前事件还剩余多少时间,回调等,每次有新节点时,重新更新节点时间。在计数到来后,重新恢复节点初始时间实现重复计时,删除相对简单,挪掉节点即可。

函数原型

int set_timer(struct own_timer **t, struct timeval val, callback* cb, void* arg) ;
int free_timer(struct own_timer* timer) ;

源码

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <signal.h>
#include <errno.h>
#include <sys/time.h>
#include <pthread.h>


#define MIN(a,b) (((a) < (b))?(a):(b))




typedef void (*callback)(void* argc);

typedef struct list {
    void* next;
    void* prev;
} LIST_ENTRY;

struct own_timer {
    LIST_ENTRY entry;
    int handle;
    struct timeval left_dyn;
    struct timeval left_init;
    callback* cb;
    void* cb_arg;
};

static LIST_ENTRY *head = NULL;
static LIST_ENTRY *tail = NULL;
static struct timeval last_set;
static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
static int test = 0;

static struct own_timer *t1 = NULL;
static struct own_timer *t2 = NULL;
static struct own_timer *t3 = NULL;


void timeout(void* arg)
{
    printf("timeout %d >>\n",(int)arg);
}

void timeout4(void* arg)
{
    printf("timeout4 >>>>>>>>>\n");
    test ++;
}

static int compare_time(struct timeval a, struct timeval b)
{
    if(a.tv_sec > b.tv_sec)
        return 1;
    else if(a.tv_sec == b.tv_sec && a.tv_usec > b.tv_usec) 
        return 1;
    else if(a.tv_sec == b.tv_sec && a.tv_usec == b.tv_usec) 
        return 0;
    else
        return -1;
}

static int diff_time(struct timeval* result, struct timeval* old,struct  timeval* newt)
{
    if(compare_time(*old,*newt) < 0) {
        //printf("old shoud bigger\n");
        return -
  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值