📄 timer.c
字号:
#include <errno.h>#include <stdlib.h>#include <sys/intr.h>#include <sys/time.h>#include <sys/timer.h>#define TIMER_NAME_LEN 32#define TIMERS 16typedef struct timer { char name[TIMER_NAME_LEN]; struct timeval tv; struct timeval period; timer_func_t f; void *arg; struct timer *next;} *timer_t;static struct timer timertab[TIMERS];static timer_t timers = NULL;static voidtimer_clear(timer_t timer){ timerclear(&(timer->tv)); timerclear(&(timer->period)); timer->f = NULL; timer->next = NULL;}static voidtimer_insert(timer_t timer){ timer_t t; if (timers == NULL) { timers = timer; return; } /* Insert new timer at head of list */ if (timercmp(&(timer->tv), &(timers->tv), <)) { timer->next = timers; timers = timer; return; } /* Insert new timer somewhere after the head of the list */ for (t = timers; t->next != NULL; t = t->next) if (timercmp(&(timer->tv), &(t->next->tv), <)) break; timer->next = t->next; t->next = timer;}/* * This interrupt service routine is called by the clock isr. Assume * interrupts are disabled and cannot be reenabled. */voidtimer_isr(){ struct timeval now; timer_t t; utime(&(now.tv_sec), &(now.tv_usec)); for (; timers != NULL;) { if (timercmp(&now, &(timers->tv), <))break; (*(timers->f)) (); t = timers; timers = timers->next; if (timerisset(&(t->period))) //2002年10月15日修改 { timeradd(&(t->tv), &(t->period), &(t->tv)); timer_insert(t); } else { timer_clear(t); } } }voidtimer_init(){ int i; for (i = 0; i < TIMERS; i++) timer_clear(&(timertab[i]));}static timer_ttimer_alloc(){ int i; for (i = 0; i < TIMERS; i++) if (timertab[i].f == NULL) break; if (i == TIMERS) return NULL; return &(timertab[i]);}inttimer_start(char *name, timeval_t dur, timer_func_t f, void *arg){ struct timeval now; timer_t t; if (dur->tv_sec == 0 && dur->tv_usec == 0) return EINVAL; disable; t = timer_alloc(); if (t == NULL) { enable; return EAGAIN; } t->f = f; t->arg = arg; /* Compute expiration time of new timer */ utime(&(now.tv_sec), &(now.tv_usec)); timeradd(&now, dur, &(t->tv)); timer_insert(t); enable; return 0;}inttimer_loop(char *name, timeval_t period, timer_func_t f, void *arg){ struct timeval now; timer_t t; if (period->tv_sec == 0 && period->tv_usec == 0) return EINVAL; disable; t = timer_alloc(); if (t == NULL) { enable; return EAGAIN; } t->f = f; t->arg = arg; t->period.tv_sec = period->tv_sec; t->period.tv_usec = period->tv_usec; /* Compute expiration time of new timer */ utime(&(now.tv_sec), &(now.tv_usec)); timeradd(&now, period, &(t->tv)); timer_insert(t); enable; return 0;}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -