原理
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 -