在linux内核下编程,特别是驱动编程中,往往HZ的定时器精度不能满足我们的需求;此时,内核为高精度定时器重新设计了一套软件架构,它可以为我们提供纳秒级的定时精度,以满足对精确时间有迫切需求的应用程序或内核驱动,例如多媒体应用,音频设备的驱动程序等等。以下的讨论用hrtimer(high resolution timer)表示高精度定时器。,下面举一个例子予以说明:
#include
#include
#include
#include
static struct hrtimer hr_timer;
ktime_t ktime;
enum hrtimer_restart my_hrtimer_callback( struct hrtimer *timer )
{
printk( KERN_ALERT "my_hrtimer_callback called......\n");
// hrtimer_start( &timer, ktime, HRTIMER_MODE_REL ); // 如果想一直运行下去
return HRTIMER_NORESTART;
}
/* 或者是下面的回调函数*/
/*static enum hrtimer_restart hrtimer_handler(struct hrtimer *timer)
{
//kt = ktime_set(1, 10);
printk(" ------ I am in hrtimer -----\n");
hrtimer_forward(timer, timer->base->get_time(), kt);
return HRTIMER_RESTART;
}*/
static int __init my_hrtimer_init void )
{
printk( KERN_ALERT "HR Timer module installing\n");
ktime = ktime_set( 0, 200*1000); // 200us
hrtimer_init( &hr_timer, CLOCK_MONOTONIC, HRTIMER_MODE_REL );
hr_timer.function = &my_hrtimer_callback;
hrtimer_start( &hr_timer, ktime, HRTIMER_MODE_REL );
return 0;
}
static void __exit my_hrtimer_exit( void )
{
int ret;
ret = hrtimer_cancel( &hr_timer ); // 取消定时器执行
if (ret){
printk( KERN_ALERT "The timer was still in use...\n");
}
printk( KERN_ALERT "HR Timer module uninstalling\n");
return;
}
MODULE_LICENSE("GPL");
module_init(my_hrtimer_init);
modlue_exit(my_hrtimer_exit);
想了解更多关于hrtimer的API函数,请参见linux内核树~/kernel/hrtimer.c文件